我正在研究 ASP.NET core Web API。
我已经实现了注册方法并生成了JWT。 在 JWT 中,我只有具有 userId 的名称。
var tokenClaims = new List<Claim>
{
new(ClaimTypes.Name, userExist.Id),
};
var token = GetToken(tokenClaims);
var jwt = new JwtSecurityTokenHandler().WriteToken(token);
但是我在 ASPNETUSERCLAIMS 表中保存了其他声明,例如角色和其他数据。
var authClaims = new List<Claim>
{
new(ClaimTypes.Name, userExist.Id),
new(CustomClaimTypes.ChannelId, userExist.ChannelId.ToString())
};
foreach (var userRole in userRoles)
{
authClaims.Add(new Claim(ClaimTypes.Role, userRole));
}
await _userManager.AddClaimsAsync(userExist, authClaims);
我想实施
[Authorize(ClaimType = "Roles", ClaimValues = UserRoles.User]
如何实施?
您可以尝试使用
[Authorize]
属性上的 Policy 属性来指定策略名称来应用策略。
例如,注册策略作为授权服务配置的一部分进行,通常在 Program.cs 文件中:
builder.Services.AddAuthorization(options =>
{
options.AddPolicy("RolesOnly", policy =>
policy.RequireClaim("EmployeeNumber", "1", "2", "3", "4", "5"));
});
然后:
[Authorize(Policy = "RolesOnly")]
public IActionResult VacationBalance()
{
return View();
}
您可以查看ASP.NET Core 中基于声明的授权了解更多信息。