问题
I'm playing with asp.net Core implementing a little WEB API that will be consumed by an iOS/Android app. I'm using JWT tokens to authorize the users. I'm adding a role
claim upon user login that determines whether the user is an administrator or a normal user at the time of issuing the JWT, and I'm using the [Authorize(Role = '...')]
attribute to make sure that certain endpoints are only available for the respective role(s). This works fine and well so far.
The code to create the JWT looks like this (shortened):
var claims = new[]
{
new Claim(JwtRegisteredClaimNames.Sub, m_configuration["Jwt:Subject"]),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
new Claim(JwtRegisteredClaimNames.Iat, DateTime.UtcNow.ToString()),
new Claim("Id", user.Id.ToString()),
new Claim("FirstName", user.FirstName),
new Claim("LastName", user.LastName),
new Claim("UserName", user.UserName),
new Claim("role", user.IsAdmin ? "Admin" : "User"),
new Claim("EMail", user.EMail)
};
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(m_configuration["Jwt:Key"]));
var signingCredentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
return new JwtSecurityToken(m_configuration["Jwt:Issuer"], m_configuration["Jwt:Audience"], claims, expires: expiration, signingCredentials: signingCredentials);
But I wonder:
I would like to allow admins to grant/revoke the admin rights to/from other users. Currently, the service side determines the admin status from the JWT by default. How would I make it recognize that the user is actually an admin/no longer an admin even though the JWT says something else?
I don't see a chance to do so until I refresh their JWT, but that doesn't seem to be a good approach. Is there some point in the "chain" on the service side where I can determine the role for the JWT's user dynamically and add the respective role, allowing me to skip the role
claim in the first place?
来源:https://stackoverflow.com/questions/64633941/jwt-changing-a-users-role-after-authentication