c# - WebAPI/Owin - 登录后身份未被授权

标签 c# asp.net authentication cookies asp.net-web-api

我正在使用 WebAPI/Owin 3.0 实现简单的登录名/密码身份验证。这是我的配置方法:

public void ConfigureAuth(IAppBuilder app) {
    // Configure the db context and user manager to use a single instance per request
    app.CreatePerOwinContext(ApplicationDbContext.Create);
    app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);

    app.UseCookieAuthentication(new CookieAuthenticationOptions() {
        AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
        LoginPath = new PathString("/#sign-in")
    });
}

这是登录方法

[Authorize]
[RoutePrefix("api/Account")]
public class AccountController : ApiController {

    [AllowAnonymous]
    [Route("Login")]
    public async Task<IHttpActionResult> Login(LoginBindingModel login) {
        ApplicationUser user = await UserManager.FindAsync(login.Email, login.Password);
        if(user != null) {
            var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);        
            Authentication.SignIn(new AuthenticationProperties() { IsPersistent = true }, identity);
            return Ok("OK");
        }

        return BadRequest("Invalid email or password");
    }

}

在我向登录方法发送请求后,我可以看到来自服务器的身份验证 cookie。我还看到在发送进一步的请求时,cookie 被发送回服务器。但是,服务器返回 401 Unauthorized 响应。

我在 AuthorizeAttribute.IsAuthorized 方法中放置了一个断点。结果表明 actionContext.ControllerContext.RequestContext.Principal.Identity.IsAuthenticated == false 因为 AuthenticationType 为 null 并且没有声明。 Login 方法中的原始标识有 4 个声明,其 IsAuthenticated 属性为真。

为什么 Identity 会丢失其所有 Claims 和 AuthenticationType 值?

我正在使用本地 IISExpress 服务器和在本地主机域上运行的应用程序进行测试。

最佳答案

原来是Cookie认证与SuppressDefaultHostAuthentication选项冲突。在 WebApiConfig.cs 中禁用它以解决问题。

config.SuppressDefaultHostAuthentication();

关于c# - WebAPI/Owin - 登录后身份未被授权,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27294032/

相关文章:

c# - 为什么我不能将通用列表声明为可为空?

c# - 将鼠标悬停在该用户控件中的任何控件上时,每个标签的文本都会变为红色

c# - 点击事件中的 ajax 请求后重定向

sql - 仅当项目属于所有者时才插入序列

php - CI - Flexi Auth,$this->flexi_auth->insert_user() 显示 "Creating default object from empty value"错误

c# - 源不包含使用 Linq 的数据行

c# - 性能计数器 NextValue 返回相同的先前值

c# - 没有用户名/密码的 Exchange Web 服务授权

c# - .NET 中是否可以使用 C# 实现基于事件的异步模式而无需多线程?

asp.net - 将服务器端事件添加到扩展器控件