JWT: Changing a user's role after authentication

不问归期 提交于 2020-12-06 16:55:31

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!