[英]ASP.NET Identity redirecting after login before user roles are established
我的登錄信息幾乎是Identity標准代碼。 我添加了一些東西來做我需要的事情,但是在大多數情況下,登錄代碼仍未編輯:
var result = signinManager.PasswordSignIn(User.UserName, Password.Text, RememberMe.Checked, shouldLockout: false);
switch (result)
{
case SignInStatus.Success:
// Store the user's supplier Id (if it exists - i.e. user is not an admin).
using (ApplicationDbContext Context = new ApplicationDbContext())
{
Session["UserId"] = User.Id;
}
IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
break;
}
我在IdentityHelper
修改了重定向,以根據其角色將用戶帶到此處或那里:
public static void RedirectToReturnUrl(string returnUrl, HttpResponse response)
{
if (!String.IsNullOrEmpty(returnUrl) && IsLocalUrl(returnUrl))
{
response.Redirect(returnUrl);
}
else
{
if (HttpContext.Current.User.IsInRole("Supplier"))
response.Redirect("~/Members/Supplier.aspx");
if (HttpContext.Current.User.IsInRole("Admin"))
response.Redirect("~/Members/Admin.aspx");
if (HttpContext.Current.User.IsInRole("Consultant"))
response.Redirect("~/Members/Consultant.aspx");
}
}
問題是,當我第一次以新用戶身份登錄(即我以管理員身份登錄,注銷並嘗試以供應商身份登錄)時,由於HttpContext.Current.User.IsInRole("Supplier")
返回false。
如果我立即使用相同的登錄憑據再次嘗試,則可以正常工作,因此在我看來,系統嘗試重定向的時間過早,而登錄實際上並未正確編譯用戶信息。
如果是這種情況,減慢速度以便僅在正確分配用戶后才嘗試重定向的最佳方法是什么?
我覺得一個簡單的do...while
循環可能效果很好:
do
{
// Literally do nothing while the condition is true.
}
while (!HttpContext.Current.User.IsAuthenticated);
不過似乎有點駭人聽聞...
身份信息存儲在cookie中。 在您的方案中,cookie尚未創建,因此HttpContext.Current.User
不包含身份信息。
do while
循環無法解決您的問題。
使用userId從數據庫中獲取用戶角色和相關數據,並根據那里的角色重定向用戶,而不是嘗試從HttpContext
獲取用戶角色和相關數據。
您可以使用UserManager.IsInRoleAsync(user.Id,"Admin")
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.