2016-04-29 94 views
0

我正在研究asp.net應用程序。我有4個角色aspnetroles表:使用aspnet身份登錄時檢查用戶的角色

**Id Name** 
1 Admin 
4 Consumer 
2 Provider 
3 SaleUser 

在的AccountController註冊操作方法,我已經加入這個:

var user = new ApplicationUser { UserName = model.Email, Email = model.Email}; 
       var result = await UserManager.CreateAsync(user, model.Password); 
       **UserManager.AddToRole(user.Id, model.UserRole);** 

現在我檢查而登錄在這樣的登陸行動的結果:

我發現aspnetusers和aspnetuseroles表有正確的數據。

var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false); 


    if (User.IsInRole(model.UserRole)) 
          return RedirectToLocal(returnUrl); 

但條件失敗。我如何檢查用戶是否屬於特定角色。

我在Startup.cs ConfigureAuth方法添加以下行:

app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create); 

和這個類在identityConfig類:

public class ApplicationRoleManager : RoleManager<IdentityRole> 
    { 
     public ApplicationRoleManager(IRoleStore<IdentityRole, string> store) : base(store) 
     { 
     } 
     public static ApplicationRoleManager Create(IdentityFactoryOptions<ApplicationRoleManager> options, IOwinContext context) 
     { 
      var roleStore = new RoleStore<IdentityRole>(context.Get<ApplicationDbContext>()); 
      return new ApplicationRoleManager(roleStore); 
     } 
    } 

和這些代碼的AccountController:

private ApplicationRoleManager roleManager; 
     public ApplicationRoleManager RoleManager 
     { 
      get 
      { 
       return this.roleManager ?? HttpContext.GetOwinContext().Get<ApplicationRoleManager>(); 
      } 
      private set { this.roleManager = value; } 
     } 

但仍然是相同的問題

更新

變種用戶=新ClaimsPrincipal(AuthenticationManager.AuthenticationResponseGrant.Identity);

    if (User.IsInRole(model.UserRole)) 
         return RedirectToLocal(returnUrl); 
        else 
        { 

         AuthenticationManager.AuthenticationResponseGrant = null; 

         model.Roles = GetRoles(); 
         ModelState.AddModelError("", "You cannot login as " + model.UserRole); 
         return View(model); 
        } 
+0

在更新後的代碼段中會出現'if(User.IsInRole(model.UserRole))'類型錯誤嗎? –

回答

1

請試試這個

if (result == SignInStatus.Success) 
{ 
    var user = new ClaimsPrincipal(AuthenticationManager.AuthenticationResponseGrant.Identity); 

    if (user.IsInRole(model.UserRole)) 
    {  
     return RedirectToLocal(returnUrl); 
    } 
    else 
    { 
     AuthenticationManager.AuthenticationResponseGrant = null; 
     model.Roles = GetRoles(); 
     ModelState.AddModelError("", "You cannot login as " + model.UserRole); 
     return View(model); 
    } 
} 

ModelState.AddModelError("", "Invalid login attempt."); 
return View(model); 

的問題是,User取決於您已經發送到瀏覽器的cookie創建的,但在這一點上,你還沒有給他們呢。

+0

謝謝。這工作。只有一個問題。如果我選擇錯誤角色,則會收到錯誤消息,之後當我嘗試再次登錄時,我收到此消息「提供的防僞令牌是針對與當前用戶不同的基於聲明的用戶。」 –

+0

@ user1125955得到了你的觀點,更新了我的解決方案 –

+0

@ user1125955問題是,當角色錯誤時,只需將'AuthenticationManager.AuthenticationResponseGrant'設置爲'null' –