在 Identity Core 中具有角色的 JWT 授权

JWT authorization with roles in Identity Core

我无法理解 Identity Core

中的 Roles

我的 AccountController 看起来像这样,我在 GenerateJWTToken 方法的声明中添加了 Roles

[HttpPost("Login")]
    public async Task<object> Login([FromBody] LoginBindingModel model)
    {
        var result = await this.signInManager.PasswordSignInAsync(model.UserName, model.Password, false, false);

        if (result.Succeeded)
        {
            var appUser = this.userManager.Users.SingleOrDefault(r => r.UserName == model.UserName);
            return await GenerateJwtToken(model.UserName, appUser);
        }

        throw new ApplicationException("INVALID_LOGIN_ATTEMPT");
    }

    [HttpPost("Register")]
    public async Task<object> Register([FromBody] RegistrationBindingModel model)
    {
        var user = new ApplicationUser
        {
            UserName = model.UserName,
            Email = model.Email,
            FirstName = model.FirstName,
            LastName = model.LastName
        };
        var result = await this.userManager.CreateAsync(user, model.Password);

        if (result.Succeeded)
        {
            await this.signInManager.SignInAsync(user, false);
            return await this.GenerateJwtToken(model.UserName, user);
        }

        throw new ApplicationException("UNKNOWN_ERROR");
    }

    private async Task<object> GenerateJwtToken(string userName, IdentityUser user)
    {
        var claims = new List<Claim>
        {
            new Claim(JwtRegisteredClaimNames.Sub, userName),
            new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
            new Claim(ClaimTypes.NameIdentifier, user.Id),
            new Claim(ClaimTypes.Role, Role.Viewer.ToString()),
            new Claim(ClaimTypes.Role, Role.Developer.ToString()),
            new Claim(ClaimTypes.Role, Role.Manager.ToString())
        };

        var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(this.configuration["JwtKey"]));
        var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
        var expires = DateTime.Now.AddDays(Convert.ToDouble(this.configuration["JwtExpireDays"]));

        var token = new JwtSecurityToken(
            this.configuration["JwtIssuer"],
            this.configuration["JwtIssuer"],
            claims,
            expires: expires,
            signingCredentials: creds);

        return new JwtSecurityTokenHandler().WriteToken(token);
    }

根据这段代码,我的令牌与 [Authorize] 控制器的属性完美配合。

我的问题是,在哪个步骤中将 role 添加到我注册的 user 以使用(例如)[Authorize("Admin")]?如何将 role 保存到数据库?

[Route("api/[controller]")]
[Authorize] //in this form it works ok, but how to add roles to it with JWT Token?
            //how to register user to role and get this role to JWT Token?
[ApiController]
public class DefaultController : ControllerBase

我的ApplicationUser:

public class ApplicationUser : IdentityUser
{
    public string FirstName { get; set; }

    public string LastName { get; set; }
}

Roles 的枚举:

public enum Role
{
    Viewer,
    Developer,
    Manager
}

如何将有关用户角色的信息保存到身份数据库,并在登录时使该角色正常工作 [Authorize] 属性?

编辑:

我想做的是像在我的用户枚举中一样存储 Roles。我想将用户注册为 DeveloperManager 等。我相信我可以通过 ApplicationUser 并添加 Role 属性 来完成,但我无法从中获得按属性授权 [Authorization(role)]

您不需要在您的案例中使用 IdentityUser 和身份数据库,您使用的是 JWT。使用已定义的 Roles 属性 创建您的 User 模型并简单地将其保存在数据库中。喜欢:

public class User
{
   public string FirstName { get; set; }
   public string LastName { get; set; }
   public Role Role { get; set; }
}

public enum Role
{
   Viewer,
   Developer,
   Manager
}

令牌:

var user = // ...
var tokenHandler = new JwtSecurityTokenHandler();
var key = Encoding.ASCII.GetBytes(your_seccret_key);
var tokenDescriptor = new SecurityTokenDescriptor
{
    Subject = new ClaimsIdentity(new Claim[] 
         {
             new Claim(ClaimTypes.Name, user.FirstName),
             new Claim(ClaimTypes.Name, user.LastName),
             new Claim(ClaimTypes.Role, user.Role)
         }),
     Expires = DateTime.UtcNow.AddDays(1),
     SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key),SecurityAlgorithms.HmacSha256Signature)
 };
 var token = tokenHandler.CreateToken(tokenDescriptor);
 user.Token = tokenHandler.WriteToken(token);

控制器方法:

[Authorize(Roles = Role.Developer)]
[HttpGet("GetSomethingForAuthorizedOnly")]
public async Task<object> GetSomething()
{ 
   // .... todo
}

您可以将内置角色管理与 ASP.NET 身份结合使用。由于您使用的是 ASP.NET Core 2.1 ,您可以首先参考下面 link 以在身份系统中启用角色:

启用角色后,您可以注册roles/users,然后为用户添加角色,如:

private async Task CreateUserRoles()
{   
    IdentityResult roleResult;
    //Adding Admin Role
    var roleCheck = await _roleManager.RoleExistsAsync("Admin");
    if (!roleCheck)
    {

        IdentityRole adminRole = new IdentityRole("Admin");
        //create the roles and seed them to the database
        roleResult = await _roleManager.CreateAsync(adminRole);

        _roleManager.AddClaimAsync(adminRole, new Claim(ClaimTypes.AuthorizationDecision, "edit.post")).Wait();
        _roleManager.AddClaimAsync(adminRole, new Claim(ClaimTypes.AuthorizationDecision, "delete.post")).Wait();

        ApplicationUser user = new ApplicationUser {
            UserName = "YourEmail", Email = "YourEmail",

        };
        _userManager.CreateAsync(user, "YourPassword").Wait();

        await _userManager.AddToRoleAsync(user, "Admin");
    }

}

这样当该用户登录到您的应用程序时,您可以在 ClaimsPrincipal 中找到 role 声明,并且它与 Authorize 具有角色的属性一起使用。