【发布时间】:2021-08-10 03:58:42
【问题描述】:
我已经在我的 .net 核心应用程序中设置了授权和身份验证。我正在创建我的 JWT 令牌并添加一个角色:
public async Task<IActionResult> Login([FromBody] LoginModel model)
{
var user = await userManager.FindByNameAsync(model.Username);
if(user!=null && await userManager.CheckPasswordAsync(user, model.Password))
{
var authClaims = new[]
{
new Claim(JwtRegisteredClaimNames.Sub, user.UserName),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
new Claim(ClaimTypes.Role,"Employee")
};
var authSignKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("*******************"));
var token = new JwtSecurityToken(
issuer: "https://example.com",
audience: "https://example.com",
expires: DateTime.Now.AddDays(5),
claims: authClaims,
signingCredentials: new Microsoft.IdentityModel.Tokens.SigningCredentials(authSignKey, SecurityAlgorithms.HmacSha256)
);
return Ok(new
{
token = new JwtSecurityTokenHandler().WriteToken(token),
expiration = token.ValidTo
});
}
return Unauthorized();
}
我现在添加了声明类型角色并分配给“员工”。在我的控制器中,我有这个:整个控制器上的装饰:
[Authorize(Roles ="Employee")]
[ApiController]
[Route("[controller]")]
我也只是将 Authorize 放在控制器上,将 Authorize(Roles="Employee") 放在我正在使用的 Get() 方法上。我可以生成 JWT,当我在 Jwt.io 上查看它时,我会看到:
{
"sub": "test",
"jti": "f3c204d4-151f-402a-bdf5-6574934d4644",
"http://schemas.microsoft.com/ws/2008/06/identity/claims/role": "Employee",
"exp": 1621968453,
"iss": "https://example.com",
"aud": "https://example.com"
}
所以它正在被编码。我看不到我缺少什么,我需要为登录分配角色以控制对方法的访问。
【问题讨论】: