2016-04-29 74 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' –

相关问题