使用aspnet标识在登录期间检查用户的角色

时间:2016-04-29 12:15:24

标签: c# asp.net

我正在开发asp.net应用程序。我有一个有四个角色的aspnetroles表:

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

在AccountController Register Action方法中,我添加了这个:

 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; }
        }

但仍然是同一个问题

更新

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);
}

1 个答案:

答案 0 :(得分:3)

请试试这个

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创建的,但此时您还没有发送它们。