• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

通过ASP.NET核心身份的角色声明进行JWT身份验证

用户头像
it1352
帮助1

问题说明

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

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?

正确答案

#1

要将角色添加到声明中,您需要使用声明类型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")] 

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /reply/detail/tanhcfhjbe
系列文章
更多 icon
同类精品
更多 icon
继续加载