AuthenticationManager.SignIn() 未登录
AuthenticationManager.SignIn() is not signing in
我可以从数据库中获取有效用户,创建 ClaimsIdentity
并且调用 SignIn
方法没有错误。
public ActionResult SignInConformation(SignInModel model)
{
if (ModelState.IsValid)
{
var user = _userManager.Find(model.Username, model.Password);
if (user == null)
{
ModelState.AddModelError("", "Invalid username and\or password");
}
else
{
_authenticationManager.SignOut();
var claimsIdentity = _userManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);
_authenticationManager.SignIn(new AuthenticationProperties { IsPersistent = true }, claimsIdentity);
return RedirectToAction("Index", "Home");
}
}
return View();
}
但是,当我检查用户是否已在这样的视图上登录时:
<p>
Current User: @if (User.Identity.IsAuthenticated)
{
@User.Identity.Name
}
else
{
@:Unknown
}
</p>
IsAuthenticated
returns false
.
我缺少来自 OWIN 启动 class 的 AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie
:
var authenticationOptions = new CookieAuthenticationOptions
{
LoginPath = new PathString("/Account/SignIn"),
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie
};
appBuilder.UseCookieAuthentication(authenticationOptions);
遗憾的是没有一个好的、有用的错误。我不喜欢默默失败的程序。
我遇到了同样的问题 - 问题是我的家庭控制器受到 [Authorize(Roles = "Administrator")] 属性的保护,而我试图以用户身份登录。
我可以从数据库中获取有效用户,创建 ClaimsIdentity
并且调用 SignIn
方法没有错误。
public ActionResult SignInConformation(SignInModel model)
{
if (ModelState.IsValid)
{
var user = _userManager.Find(model.Username, model.Password);
if (user == null)
{
ModelState.AddModelError("", "Invalid username and\or password");
}
else
{
_authenticationManager.SignOut();
var claimsIdentity = _userManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);
_authenticationManager.SignIn(new AuthenticationProperties { IsPersistent = true }, claimsIdentity);
return RedirectToAction("Index", "Home");
}
}
return View();
}
但是,当我检查用户是否已在这样的视图上登录时:
<p>
Current User: @if (User.Identity.IsAuthenticated)
{
@User.Identity.Name
}
else
{
@:Unknown
}
</p>
IsAuthenticated
returns false
.
我缺少来自 OWIN 启动 class 的 AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie
:
var authenticationOptions = new CookieAuthenticationOptions
{
LoginPath = new PathString("/Account/SignIn"),
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie
};
appBuilder.UseCookieAuthentication(authenticationOptions);
遗憾的是没有一个好的、有用的错误。我不喜欢默默失败的程序。
我遇到了同样的问题 - 问题是我的家庭控制器受到 [Authorize(Roles = "Administrator")] 属性的保护,而我试图以用户身份登录。