我正在使用 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 Unauthorized 响应。
我在 AuthorizeAttribute.IsAuthorized 方法中放置了一个断点。事实证明
actionContext.ControllerContext.RequestContext.Principal.Identity.IsAuthenticated == false,因为 AuthenticationType 为 null 并且没有声明。 Login 方法中的原始身份有 4 个声明,并且其 IsAuthenticated 属性为 true。
为什么身份会丢失所有的 Claims 和 AuthenticationType 值?
我正在使用本地 IISExpress 服务器和在本地主机域上运行的应用程序进行测试。