通过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")]
这篇好文章是转载于:学新通技术网
- 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
- 本站站名: 学新通技术网
- 本文地址: /reply/detail/tanhcfhjbe
-
YouTube API 不能在 iOS (iPhone/iPad) 工作,但在桌面浏览器工作正常?
it1352 07-30 -
iPhone,一张图像叠加到另一张图像上以创建要保存的新图像?(水印)
it1352 07-17 -
保持在后台运行的 iPhone 应用程序完全可操作
it1352 07-25 -
使用 iPhone 进行移动设备管理
it1352 07-23 -
在android同时打开手电筒和前置摄像头
it1352 09-28 -
扫描 NFC 标签时是否可以启动应用程序?
it1352 08-02 -
检查邮件是否发送成功
it1352 07-25 -
Android微调工具-删除当前选择
it1352 06-20 -
希伯来语的空格句子标记化错误
it1352 06-22 -
Android App 和三星 Galaxy S4 不兼容
it1352 07-20