通过ASP.NET核心身份中的角色声明进行JWT身份验证 [英] JWT Authentication by role claims in ASP.NET core Identity

查看:565
本文介绍了通过ASP.NET核心身份中的角色声明进行JWT身份验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何通过包含用户角色的声明对用户进行身份验证?

How I can authenticate user by claims, which contains in user roles?

Startup.cs中:

services.AddAuthorization(options => {
                options.AddPolicy("CanEdit", policy => policy.RequireClaim("CanEdit"));    
});

在登录控制器中,我有:

And in login controller I have:

    private async ValueTask<JwtSecurityToken> GetJwtSecurityToken(ApplicationUser user){
        //var totalClaims = new List<Claim>();
        //var userRoles = await _userManager.GetRolesAsync(user);
        //foreach (var role in userRoles) {
        //    var roleClaims = await _roleManager.GetClaimsAsync(await _roleManager.Roles.SingleAsync(r => r.Name.Equals(role)));
        //    totalClaims.AddRange(roleClaims);
        //}
        var claims = new List<Claim>
        {
            new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
            new Claim(JwtRegisteredClaimNames.Sub, user.UserName),
            new Claim(JwtRegisteredClaimNames.Email, user.Email)
        };
        return new JwtSecurityToken(
            _configuration["Token:Issuer"],
            _configuration["Token:Audience"],
            //totalClaims,
            claims
            expires: DateTime.UtcNow.AddHours(12),
            signingCredentials: new SigningCredentials(
                new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Token:Key"])),
                SecurityAlgorithms.HmacSha256)
        );
    }

方法policy.RequireClaim以令牌而不是角色搜索声明.

Method policy.RequireClaim search claims in token, not in role.

当我取消注释时,它会起作用. 这是一个好的解决方案吗?

When I uncomment the lines, it works. Is this a good solution?

推荐答案

要将角色添加到声明中,您需要使用声明类型Role,例如:

To add roles to claims, you'll need use claim type Role, like so:

var rolesList = new List<string>
    {
     "Admin",
     "SuperUser",
     "Etc..."
    };


foreach (var role in rolesList)
    {
     claims.Add(new Claim(ClaimTypes.Role, role));
    }

注意:创建令牌时,请确保添加了声明.

NB:- when creating token ensure claims are added.

var Token = new JwtSecurityToken(
    issuer: "localhost",
    audience: "localhost",
    expires: DateTime.Now.AddMinutes(10),
    claims:claims //claims added to token here!
    signingCredentials: Creds);
    return new JwtSecurityTokenHandler().WriteToken(Token);
    }

就是这样,现在您可以通过Authorize属性测试令牌是否包含角色"Admin".

That's it, now you can test if the token contains the role "Admin" via the Authorize attribute.

   [Authorize(Roles="Admin")]

NB:-要针对多个角色进行测试(令牌包含声明"Admin"或"SuperUser")

NB:- To test against multiple roles (the token contains the claim "Admin" or "SuperUser")

  [Authorize(Roles="Admin","SuperUser")]

下面@gentiane指出的编辑

EDIT as pointed out by @gentiane below

  [Authorize(Roles="Admin,SuperUser")] 

这篇关于通过ASP.NET核心身份中的角色声明进行JWT身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆