如何在角色声明中存储多个角色?

时间:2019-08-01 09:52:43

标签: c# asp.net-core

claims.Add(new Claim(ClaimTypes.Role, string.Join(",", user.UserRoles.Select(ur => ur.Role.Nome))));

但是,如果我这样做

User.IsInRole("myRole")

它返回假

1 个答案:

答案 0 :(得分:3)

您可以做到

Claim[] claims = new Claim[] 
{
          new Claim(ClaimTypes.Role, "User"),
          new Claim(ClaimTypes.Role, "Dev"), 
          new Claim(ClaimTypes.Role,"QA"),
          new Claim(ClaimTypes.Role,"DBA")
};

或者您可以使用RoleManager来做到这一点。您可以使用角色管理器来添加角色,而不是通过使用Claim将每个角色与逗号连接起来。但是,在使用角色管理器之前,请确保已在Startup.cs中正确注册了它。

Startup.cs

 services.AddIdentity<AppUser, IdentityRole<string>>(options =>
             {
                 options.Password.RequireDigit = false;
                 options.Password.RequiredLength = 4;
                 options.Password.RequireLowercase = false;
                 options.Password.RequireNonAlphanumeric = false;
                 options.Password.RequireUppercase = false;

                 options.User.RequireUniqueEmail = true;

             })
                .AddRoles<IdentityRole<string>>()
                .AddEntityFrameworkStores<AppIdentityDbContext>()
                .AddRoleManager<RoleManager<IdentityRole<string>>>()
                .AddDefaultTokenProviders();

在数据库环境中,请确保还包括IdentityRole或IdentityRole。

AppIdentityDbContext.cs(自定义名称)

 public class AppIdentityDbContext:
        IdentityDbContext<AppUser,IdentityRole<string>,string>
    {
        public AppIdentityDbContext(DbContextOptions<AppIdentityDbContext> options)
            : base(options)
        {

        }
    }

要添加角色,可以在AccountController或所需的其他控制器中指定。确保使用RoleManager。在此代码段中,请确保您注意“注册”操作,您可以看到如何在其中添加新角色。

AccountController.cs

    public class AccountController : Controller
        {
            private readonly UserManager<AppUser> _userManager;
            private readonly SignInManager<AppUser> _signInManager;
            private readonly RoleManager<IdentityRole<string>> _roleManager;

            public AccountController(
                UserManager<AppUser> userManager,
                SignInManager<AppUser> signInManager,
                RoleManager<IdentityRole<string>> roleManager)
            {
                _userManager = userManager;
                _signInManager = signInManager;
                _roleManager = roleManager;
            }

            public IActionResult Register()
            {
                return View();
            }

            [HttpPost]
            [ValidateAntiForgeryToken]
            public async Task<IActionResult> Register(RegisterViewModel model)
            {
                if(ModelState.IsValid)
                {
                    AppUser user = new AppUser
                    {
                        FullName = model.FullName,
                        Email = model.Email,
                        UserName = model.Email
                    };
                    var createResult = await _userManager.CreateAsync(user, model.Password);
                    if(createResult.Succeeded)
                    {
                        await _userManager.AddClaimAsync(user, new Claim("sys:FullName", model.FullName));
                        if(!await _roleManager.RoleExistsAsync("User"))
                        {
                            await _roleManager.CreateAsync(new IdentityRole("User"));
                        }
if(!await _roleManager.RoleExistsAsync("Dev"))
                        {
                            await _roleManager.CreateAsync(new IdentityRole("Dev"));
                        }
                        await _userManager.AddToRoleAsync(user, "User");
                        await _userManager.AddToRoleAsync(user, "Dev");
                        string token = await _userManager.GenerateEmailConfirmationTokenAsync(user);
                        string url = Url.Action("ConfirmEmail", "Account", new
                        {
                            email = model.Email,
                            token
                        }, Request.Scheme);
                        System.IO.File.WriteAllText("ConfirmEmail.txt", url);
                        return RedirectToAction(nameof(Confirmation), new
                        {
                            confirmation = ConfirmationStatus.EmailConfirmation
                        });
                    }
                    foreach(var error in createResult.Errors)
                    {
                        ModelState.AddModelError("", error.Description);
                    }
                }

                return View(model);
            }