我正在使用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域上。