Iva*_*tin 4 c# asp.net authentication cookies asp.net-web-api
我正在使用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")
});
}
Run Code Online (Sandbox Code Playgroud)
这是Login方法
[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");
}
}
Run Code Online (Sandbox Code Playgroud)
在向Login方法发送请求后,我可以看到来自服务器的身份验证cookie.我还看到在发送进一步请求时将cookie发送回服务器.但是,服务器返回401 Unauthorized响应.
我在AuthorizeAttribute.IsAuthorized方法中加了一个断点.事实证明,actionContext.ControllerContext.RequestContext.Principal.Identity.IsAuthenticated == false,因为AuthenticationType为null且没有声明.Login方法中的原始标识有4个声明,其IsAuthenticated属性为true.
为什么Identity会丢失其所有Claims和AuthenticationType值?
我正在测试使用本地IISExpress服务器与在localhost域上运行的应用程序.
Iva*_*tin 12
事实证明,Cookie身份验证与SuppressDefaultHostAuthentication选项冲突.在WebApiConfig.cs中禁用它以解决问题.
config.SuppressDefaultHostAuthentication();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2068 次 |
| 最近记录: |