WebAPI / Owin - 登录后未经授权的身份验证

4

我正在使用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");
    }

}

我在向Login方法发送请求后,可以看到来自服务器的身份验证cookie。当我发送进一步的请求时,我也看到该cookie被发送回服务器。但是,服务器返回401未经授权的响应。
我在AuthorizeAttribute.IsAuthorized方法中设置了一个断点。结果发现,actionContext.ControllerContext.RequestContext.Principal.Identity.IsAuthenticated == false,因为AuthenticationType为空且没有任何声明。在Login方法中的原始标识具有4个声明,并且其IsAuthenticated属性为true。
为什么Identity会失去所有它的声明和AuthenticationType值?
我使用本地IISExpress服务器进行测试,应用程序运行在localhost域上。
1个回答

12

原来发现Cookie身份验证与SuppressDefaultHostAuthentication选项冲突。在WebApiConfig.cs中禁用它可以解决问题。

config.SuppressDefaultHostAuthentication();

我曾经意识到这一点,但昨天这困扰了我两个小时,直到我找到了这篇文章。 - hunter

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接