我正在使用WebAPI/Owin 3.0实施简单的登录/密码身份验证。下面是我的配置方法:WebAPI/Owin - 身份登录后未获得授权
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未经授权的响应。
我把一个断点放入AuthorizeAttribute.IsAuthorized方法。原来, actionContext.ControllerContext.RequestContext.Principal.Identity.IsAuthenticated == false,因为AuthenticationType为null并且没有声明。 Login方法中的原始身份有4个声明,其IsAuthenticated属性为true。
为什么身份失去了所有的声明和AuthenticationType值?
我使用本地IISExpress服务器测试本地域名上运行的应用程序。
我在过去的某个时候意识到了这一点,但是这让我困扰了2个小时,直到我发现这篇文章。 – hunter 2015-12-03 13:45:09