我正在尝试实施Cookie身份验证。这是我的登录操作:
public async Task<IHttpActionResult> Login([FromBody]string email)
{
var user = await UserManager.FindByNameAsync(email);
Authentication.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
var identity =
await UserManager.CreateIdentityAsync(user,
DefaultAuthenticationTypes.ApplicationCookie);
// identity.IsAuthenticated is true, why?
Authentication.SignIn(identity); // identity is correct (name is user@user.com), i checked it
// User.Identity.IsAuthenticated is false here
return Ok();
}
身份验证是:
private IAuthenticationManager Authentication
{
get
{
return HttpContext.GetOwinContext().Authentication;
}
}
但User.Identity.Name仍为空。我做错了什么?我如何获得经过身份验证的用户?
这是我的Startup.Auth:
public partial class Startup
{
static Startup()
{
var userManager = new UserManager<IdentityUser>(new UserStore<IdentityUser>(new MyDbContext()));
userManager.UserValidator = new UserValidator<IdentityUser>(userManager)
{
AllowOnlyAlphanumericUserNames = false,
};
UserManagerFactory = () => userManager;
}
public static Func<UserManager<IdentityUser>> UserManagerFactory { get; set; }
public void ConfigureAuth(IAppBuilder app)
{
app.UseCookieAuthentication(new CookieAuthenticationOptions());
}
}
答案 0 :(得分:0)
尝试像这样设置SignIn方法
private IAuthenticationManager AuthenticationManager
{
get
{
return HttpContext.GetOwinContext().Authentication;
}
}
public async Task<IHttpActionResult> Login([FromBody]string email)
{
var user = await UserManager.FindByNameAsync(email);
Authentication.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity);
return Ok();
}
答案 1 :(得分:0)
解决方案是删除以下代码:
Authentication.SignOut(DefaultAuthenticationTypes.ApplicationCookie);