我正在使用 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");
}
}
在我向登录方法发送请求后,我可以看到来自服务器的身份验证 cookie。我还看到在发送进一步的请求时,cookie 被发送回服务器。但是,服务器返回 401 Unauthorized 响应。
我在 AuthorizeAttribute.IsAuthorized 方法中放置了一个断点。结果表明 actionContext.ControllerContext.RequestContext.Principal.Identity.IsAuthenticated == false 因为 AuthenticationType 为 null 并且没有声明。 Login 方法中的原始标识有 4 个声明,其 IsAuthenticated 属性为真。
为什么 Identity 会丢失其所有 Claims 和 AuthenticationType 值?
我正在使用本地 IISExpress 服务器和在本地主机域上运行的应用程序进行测试。
最佳答案
原来是Cookie认证与SuppressDefaultHostAuthentication选项冲突。在 WebApiConfig.cs 中禁用它以解决问题。
config.SuppressDefaultHostAuthentication();
关于c# - WebAPI/Owin - 登录后身份未被授权,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27294032/