[英]MVC 4: User.IsInRole() returns false after logout
我的MVC網站運作異常。 第一次登錄時,User.IsInRole(“ Admin”)返回true,並且一切正常。
但是,在我登錄並注銷后,當我嘗試再次登錄時,User.IsInRole(“ Admin”)始終返回false。 但是,在嘗試再次登錄后,此問題已解決。
這是代碼:
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Login(LoginModel model, string returnUrl)
{
string redirectUrl = returnUrl;
string userName = model.UserName;
UserProfile user = dbAccount.UserProfiles.Where(m => m.Email.Equals(userName, StringComparison.CurrentCultureIgnoreCase)).SingleOrDefault();
if (user != null)
{
userName = user.UserName;
}
if (ModelState.IsValid && WebSecurity.Login(userName, model.Password, persistCookie: model.RememberMe))
{
if (redirectUrl == null)
{
redirectUrl = User.IsInRole("Admin") ? "/Admin" : "/";
}
return RedirectToLocal(redirectUrl);
}
// If we got this far, something failed, redisplay form
ModelState.AddModelError("", "The user name or password provided is incorrect.");
return View(model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult LogOff()
{
WebSecurity.Logout();
Roles.DeleteCookie();
return RedirectToAction("Home", "Page");
}
我以某種方式注銷並登錄后,WebSecurity.Login()沒有賦予我正確的用戶角色。
您的問題是User.IsInRole()
方法從身份驗證cookie中序列化的身份驗證令牌獲取角色。 在您的登錄操作中,尚未解析cookie,因此User.IsInRole()
將始終返回false。
為何在首次登錄時有效:我的假設是,在您的首次登錄時您的用戶已經登錄(cookie在其中),這就是User.IsInRole("Admin")
返回true的原因。 為了在登錄之前(當您在登錄頁面上時)進行測試,請清除所有瀏覽器cookie並嘗試登錄-我假設您將獲得User.IsInRole("Admin")
為false。
但是,在我登錄並注銷后,當我嘗試再次登錄時,User.IsInRole(“ Admin”)始終返回false:注銷時,您刪除身份驗證cookie,因此在“登錄”操作中,該cookie不存在,這是User.IsInRole("Admin")
為假的原因。
由於此Cookie將在登錄后的請求上進行解析,因此您可以執行以下操作:
更新
public ActionResult Login(LoginModel model, string returnUrl)
{
string redirectUrl = returnUrl;
string userName = model.UserName;
UserProfile user = dbAccount.UserProfiles.Where(m => m.Email.Equals(userName, StringComparison.CurrentCultureIgnoreCase)).SingleOrDefault();
if (user != null)
{
userName = user.UserName;
}
if (ModelState.IsValid && WebSecurity.Login(userName, model.Password, persistCookie: model.RememberMe))
{
return this.RedirectToAction("AdminRedirect","Account", new {redirectUrl = redirectUrl});
}
// If we got this far, something failed, redisplay form
ModelState.AddModelError("", "The user name or password provided is incorrect.");
return View(model);
}
public ActionResult AdminRedirect(string redirectUrl)
{
if (redirectUrl == null)
{
redirectUrl = User.IsInRole("Admin") ? "/Admin" : "/";
}
return this.RedirectToLocal(redirectUrl);
}
這樣,在重定向AdminRedirect
檢查用戶角色,因此將在AdminRedirect
操作身份驗證cookie中進行解析並更新用戶角色。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.