WebAPI / Owin – 登录后未授权身份

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

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.Create); app.UseCookieAuthentication(new CookieAuthenticationOptions() { AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie, LoginPath = new PathString("/#sign-in") }); } 

这是Login方法

 [Authorize] [RoutePrefix("api/Account")] public class AccountController : ApiController { [AllowAnonymous] [Route("Login")] public async Task 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方法发送请求后,我可以看到来自服务器的身份validationcookie。 我还看到在发送进一步请求时将cookie发送回服务器。 但是,服务器返回401 Unauthorized响应。

我在AuthorizeAttribute.IsAuthorized方法中加了一个断点。 事实certificate,actionContext.ControllerContext.RequestContext.Principal.Identity.IsAuthenticated == false,因为AuthenticationType为null且没有声明。 Login方法中的原始标识有4个声明,其IsAuthenticated属性为true。

为什么Identity丢失了所有的Claims和AuthenticationType值?

我正在测试使用本地IISExpress服务器与在localhost域上运行的应用程序。

事实certificate,Cookie身份validation与SuppressDefaultHostAuthentication选项冲突。 在WebApiConfig.cs中禁用它以解决问题。

 config.SuppressDefaultHostAuthentication();