ASP.NET Core JWT映射角色声明到ClaimsIdentity

44

我想使用JWT来保护ASP.NET Core Web API。此外,我希望在控制器动作属性中直接从token负载中使用角色的选项。

现在,虽然我已经找到了如何使用它与策略:

Authorize(Policy="CheckIfUserIsOfRoleX")
ControllerAction()...

我更希望有一个选项可以使用像平常一样的东西:

Authorize(Role="RoleX")

角色将自动从JWT负载中映射。

{
    name: "somename",
    roles: ["RoleX", "RoleY", "RoleZ"]
}
那么,在ASP.NET Core中完成这个任务的最简单方法是什么?是否有一种通过某些设置/映射自动实现这个工作的方法(如果有,应该在哪里设置?)或者在验证令牌后,我应该拦截ClaimsIdentity的生成并手动添加角色声明(如果是这样,应该在哪里/如何执行?)?
3个回答

62

生成JWT时需要获取有效声明。以下是示例代码:

登录逻辑:

[HttpPost]
[AllowAnonymous]
public async Task<IActionResult> Login([FromBody] ApplicationUser applicationUser) {
    var result = await _signInManager.PasswordSignInAsync(applicationUser.UserName, applicationUser.Password, true, false);
    if(result.Succeeded) {
        var user = await _userManager.FindByNameAsync(applicationUser.UserName);

        // Get valid claims and pass them into JWT
        var claims = await GetValidClaims(user);

        // Create the JWT security token and encode it.
        var jwt = new JwtSecurityToken(
            issuer: _jwtOptions.Issuer,
            audience: _jwtOptions.Audience,
            claims: claims,
            notBefore: _jwtOptions.NotBefore,
            expires: _jwtOptions.Expiration,
            signingCredentials: _jwtOptions.SigningCredentials);
        //...
    } else {
        throw new ApiException('Wrong username or password', 403);
    }
}

基于 UserRolesRoleClaimsUserClaims 表(ASP.NET Identity)获取用户声明:

private async Task<List<Claim>> GetValidClaims(ApplicationUser user)
{
    IdentityOptions _options = new IdentityOptions();
    var claims = new List<Claim>
        {
            new Claim(JwtRegisteredClaimNames.Sub, user.UserName),
            new Claim(JwtRegisteredClaimNames.Jti, await _jwtOptions.JtiGenerator()),
            new Claim(JwtRegisteredClaimNames.Iat, ToUnixEpochDate(_jwtOptions.IssuedAt).ToString(), ClaimValueTypes.Integer64),
            new Claim(_options.ClaimsIdentity.UserIdClaimType, user.Id.ToString()),
            new Claim(_options.ClaimsIdentity.UserNameClaimType, user.UserName)
        };
    var userClaims = await _userManager.GetClaimsAsync(user);
    var userRoles = await _userManager.GetRolesAsync(user);
    claims.AddRange(userClaims);
    foreach (var userRole in userRoles)
    {
        claims.Add(new Claim(ClaimTypes.Role, userRole));
        var role = await _roleManager.FindByNameAsync(userRole);
        if(role != null)
        {
            var roleClaims = await _roleManager.GetClaimsAsync(role);
            foreach(Claim roleClaim in roleClaims)
            {
                claims.Add(roleClaim);
            }
        }
    }
    return claims;
}

Startup.cs 中,请将所需的策略添加到授权中:
void ConfigureServices(IServiceCollection service) {
   services.AddAuthorization(options =>
    {
        // Here I stored necessary permissions/roles in a constant
        foreach (var prop in typeof(ClaimPermission).GetFields(BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy))
        {
            options.AddPolicy(prop.GetValue(null).ToString(), policy => policy.RequireClaim(ClaimType.Permission, prop.GetValue(null).ToString()));
        }
    });
}

ClaimPermission:

public static class ClaimPermission
{
    public const string
        CanAddNewService = "Tự thêm dịch vụ",
        CanCancelCustomerServices = "Hủy dịch vụ khách gọi",
        CanPrintReceiptAgain = "In lại hóa đơn",
        CanImportGoods = "Quản lý tồn kho",
        CanManageComputers = "Quản lý máy tính",
        CanManageCoffees = "Quản lý bàn cà phê",
        CanManageBillards = "Quản lý bàn billard";
}

使用类似的代码片段获取所有预定义权限并将其插入到ASP.NET权限声明表中:
var staffRole = await roleManager.CreateRoleIfNotExists(UserType.Staff);

foreach (var prop in typeof(ClaimPermission).GetFields(BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy))
{
    await roleManager.AddClaimIfNotExists(staffRole, prop.GetValue(null).ToString());
}

我是ASP.NET的初学者,如果你有更好的解决方案,请告诉我。

而且,当我将所有声明/权限放入JWT中时,我不知道会有多糟糕。太长了吗?性能如何?我应该将生成的JWT存储在数据库中,并稍后检查它以获取有效用户的角色/声明吗?


这是完美的答案!大多数其他解决方案没有获得角色声明。 - DIG
5
ClaimPermission 对象来自哪里? - Rafael
2
如果有人正在寻找ClaimPermission,请查看编辑后的答案。 - trinvh
_jwtOptions 是从哪里来的?JtiGenerator 在对象浏览器中没有出现。不过,也许我可以为此生成一个随机字符串? - user2728841

20

这是我的工作代码!ASP.NET Core 2.0 + JWT。将角色添加到JWT令牌。

appsettings.json

"JwtIssuerOptions": {
   "JwtKey": "4gSd0AsIoPvyD3PsXYNrP2XnVpIYCLLL",
   "JwtIssuer": "http://yourdomain.com",
   "JwtExpireDays": 30
}

启动文件.cs

// ===== Add Jwt Authentication ========
JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear(); // => remove default claims
// jwt
// get options
var jwtAppSettingOptions = Configuration.GetSection("JwtIssuerOptions");
services
    .AddAuthentication(options =>
    {
        options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
        options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
        options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
    })
    .AddJwtBearer(cfg =>
    {
        cfg.RequireHttpsMetadata = false;
        cfg.SaveToken = true;
        cfg.TokenValidationParameters = new TokenValidationParameters
        {
            ValidIssuer = jwtAppSettingOptions["JwtIssuer"],
            ValidAudience = jwtAppSettingOptions["JwtIssuer"],
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtAppSettingOptions["JwtKey"])),
            ClockSkew = TimeSpan.Zero // remove delay of token when expire
        };
    });

账户控制器(AccountController.cs)

[HttpPost]
[AllowAnonymous]
[Produces("application/json")]
public async Task<object> GetToken([FromBody] LoginViewModel model)
{
    var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, false, false);

    if (result.Succeeded)
    {
        var appUser = _userManager.Users.SingleOrDefault(r => r.Email == model.Email);
        return await GenerateJwtTokenAsync(model.Email, appUser);
    }

    throw new ApplicationException("INVALID_LOGIN_ATTEMPT");
}

// create token
private async Task<object> GenerateJwtTokenAsync(string email, ApplicationUser user)
{
    var claims = new List<Claim>
    {
        new Claim(JwtRegisteredClaimNames.Sub, email),
        new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
        new Claim(ClaimTypes.NameIdentifier, user.Id)
    };

    var roles = await _userManager.GetRolesAsync(user);

    claims.AddRange(roles.Select(role => new Claim(ClaimsIdentity.DefaultRoleClaimType, role)));

    // get options
    var jwtAppSettingOptions = _configuration.GetSection("JwtIssuerOptions");

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

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

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

测试 Fiddler GetToken 方法。请求:

POST https://localhost:44355/Account/GetToken HTTP/1.1
content-type: application/json
Host: localhost:44355
Content-Length: 81

{
    "Email":"admin@admin.site.com",
    "Password":"ukj90ee",
    "RememberMe":"false"
}

调试响应令牌 https://jwt.io/#debugger-io

有效载荷数据:

{
  "sub": "admin@admin.site.com",
  "jti": "520bc1de-5265-4114-aec2-b85d8c152c51",
  "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier": "8df2c15f-7142-4011-9504-e73b4681fb6a",
  "http://schemas.microsoft.com/ws/2008/06/identity/claims/role": "Admin",
  "exp": 1529823778,
  "iss": "http://yourdomain.com",
  "aud": "http://yourdomain.com"
}

角色管理已经生效!


2
你可以用一行代码 claims.AddRange(roles.Select(role => new Claim(ClaimsIdentity.DefaultRoleClaimType, role))); 替换循环 foreach (var role in roles) … - Vadim Ovchinnikov
感谢Vadim纠正描述并提供有关循环的建议。我已经做出了更改! - dev-siberia
为什么没有使用 new Claim(JwtRegisteredClaimNames.Sub, email) 而是使用了 new Claim(JwtRegisteredClaimNames.Sub, user.Email)? - Murat Can OĞUZHAN
正确地。您只能传递ApplicationUser参数。然后将其全部提取出来以获取令牌。重构将改善我的代码。 - dev-siberia

16

为了生成JWT Tokens,我们需要使用AuthJwtTokenOptions帮助类。

public static class AuthJwtTokenOptions
{
    public const string Issuer = "SomeIssuesName";

    public const string Audience = "https://awesome-website.com/";

    private const string Key = "supersecret_secretkey!12345";

    public static SecurityKey GetSecurityKey() =>
        new SymmetricSecurityKey(Encoding.ASCII.GetBytes(Key));
}

账户控制器代码:

[HttpPost]
public async Task<IActionResult> GetToken([FromBody]Credentials credentials)
{
    // TODO: Add here some input values validations

    User user = await _userRepository.GetUser(credentials.Email, credentials.Password);
    if (user == null)
        return BadRequest();

    ClaimsIdentity identity = GetClaimsIdentity(user);

    return Ok(new AuthenticatedUserInfoJsonModel
    {
        UserId = user.Id,
        Email = user.Email,
        FullName = user.FullName,
        Token = GetJwtToken(identity)
    });
}

private ClaimsIdentity GetClaimsIdentity(User user)
{
    // Here we can save some values to token.
    // For example we are storing here user id and email
    Claim[] claims = new[]
    {
        new Claim(ClaimTypes.Name, user.Id.ToString()),
        new Claim(ClaimTypes.Email, user.Email)
    };
    ClaimsIdentity claimsIdentity = new ClaimsIdentity(claims, "Token");

    // Adding roles code
    // Roles property is string collection but you can modify Select code if it it's not
    claimsIdentity.AddClaims(user.Roles.Select(role => new Claim(ClaimTypes.Role, role)));
    return claimsIdentity;
}

private string GetJwtToken(ClaimsIdentity identity)
{
    JwtSecurityToken jwtSecurityToken = new JwtSecurityToken(
        issuer: AuthJwtTokenOptions.Issuer,
        audience: AuthJwtTokenOptions.Audience,
        notBefore: DateTime.UtcNow,
        claims: identity.Claims,
        // our token will live 1 hour, but you can change you token lifetime here
        expires: DateTime.UtcNow.Add(TimeSpan.FromHours(1)),
        signingCredentials: new SigningCredentials(AuthJwtTokenOptions.GetSecurityKey(), SecurityAlgorithms.HmacSha256));
    return new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken);
}
Startup.cs文件中,在services.AddMvc方法调用之前,在ConfigureServices(IServiceCollection services)方法中添加以下代码:
public void ConfigureServices(IServiceCollection services)
{
    // Other code here…

    services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
        .AddJwtBearer(options =>
        {
            options.TokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuer = true,
                ValidIssuer = AuthJwtTokenOptions.Issuer,

                ValidateAudience = true,
                ValidAudience = AuthJwtTokenOptions.Audience,
                ValidateLifetime = true,

                IssuerSigningKey = AuthJwtTokenOptions.GetSecurityKey(),
                ValidateIssuerSigningKey = true
            };
        });

    // Other code here…

    services.AddMvc();
}

app.UseMvc之前,将app.UseAuthentication()调用添加到Startup.csConfigureMethod中。

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    // Other code here…

    app.UseAuthentication();
    app.UseMvc();
}

现在,您可以使用[Authorize(Roles = "Some_role")]属性。

要在任何控制器中获取用户ID和电子邮件,您应该像这样执行:

int userId = int.Parse(HttpContext.User.Claims.First(c => c.Type == ClaimTypes.Name).Value);

string email = HttpContext.User.Claims.First(c => c.Type == ClaimTypes.Email).Value;

也可以通过这种方式检索userId(这是由于声明类型名称ClaimTypes.Name

int userId = int.Parse(HttpContext.User.Identity.Name);

最好将这样的代码移动到一些控制器扩展助手中:

public static class ControllerExtensions
{
    public static int GetUserId(this Controller controller) =>
        int.Parse(controller.HttpContext.User.Claims.First(c => c.Type == ClaimTypes.Name).Value);

    public static string GetCurrentUserEmail(this Controller controller) =>
        controller.HttpContext.User.Claims.First(c => c.Type == ClaimTypes.Email).Value;
}

对于您添加的任何其他声明也是如此。您应该只指定有效的键。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接