sadegh
sadegh

Reputation: 51

How to send roles of a user in jwt token in identity

I have done the token generation, but I want to send the user roles in the token as well.I also wrote some code related to sending the role, but it doesn't work properly.

I also have a problem with this prototyping. var jwtAuthorizationManager = new JWTAuthorizationManager();

This is my code

public class JWTAuthorizationManager { private readonly UserManager _userManager;

    public JWTAuthorizationManager(UserManager<User> _userManager)
    {
        this._userManager = _userManager;
    }
    public async Task<JwtFeildsDto> Authenticate(string UserName, string PasswordHash)
    {
        var user = await _userManager.FindByNameAsync(UserName);
            //پیدا کردن همه نقش های کاربر


        var roles = await _userManager.GetRolesAsync(user);
        //ایجاد تاریخ انقضای توکن
        var tokenExpireTimeStamp = DateTime.Now.AddHours(Constansts.JWT_TOKEN_EXPIRE_TIME);
        //ایجاد متغیر از کلاس مشخص شده برای ایجاد توکن و اطلاعات همراه آن
        var jwtSecurityTokenHandler = new JwtSecurityTokenHandler();
        //ایجاد آرایه ای از بایت ها به عنوان کلید توکن
        var tokenKey = Encoding.ASCII.GetBytes(Constansts.JWT_SECURITY_KEY_FOR_TOKEN);
        //از این کلاس برای نگهداری ویژگیها و اطلاعات درون توکن استفاده می شود.
        var List = new List<Claim>()
            {
                new Claim("username", UserName),
                new Claim(ClaimTypes.PrimaryGroupSid,"User Group 01")

            };
        var securityTokenDescriptor = new SecurityTokenDescriptor
        {

            Subject = new ClaimsIdentity(List),

            Expires = tokenExpireTimeStamp,

            //امضا یا اعتبارنامه یا مجوز ورود
            SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(tokenKey),SecurityAlgorithms.HmacSha256Signature)
        };

        foreach (var item in roles)
        {
            List.Add(new Claim(ClaimTypes.Role, item));  

        }

        var securityToken = jwtSecurityTokenHandler.CreateToken(securityTokenDescriptor);
        var token = jwtSecurityTokenHandler.WriteToken(securityToken);
 

            return new JwtFeildsDto
            {
                token = token,
                user_name = UserName,
                expire_time = (int)tokenExpireTimeStamp.Subtract(DateTime.Now).TotalSeconds

            };

    }
   
}

    [HttpPost]

    public async Task<IActionResult> Login([FromForm] String userName, String 
password,bool remmberMe)
    {

        if (ModelState.IsValid)
        {
            var result = await _loginService.UserLogin(userName, password,remmberMe);

            if (result == true)
            {
                var jwtAuthorizationManager = new JWTAuthorizationManager();
                var loginResult = jwtAuthorizationManager.Authenticate(userName, password);
                return Ok(loginResult);
            }
            else
            {

                return Unauthorized(MessageLib.Message.unaAuthorized);
            }
        }

        return BadRequest();

    }

enter image description here

enter image description here

Upvotes: 0

Views: 983

Answers (1)

Xinran Shen
Xinran Shen

Reputation: 9973

In the Constructor of JWTAuthorizationManager, it has a parameter UserManager<User> _userManager, So when you instantiate this class, you also need to pass the parameter type of UserManager<User> into it.

[ApiController]
[Route("[controller]")]
public class HomeController : ControllerBase
{
     private readonly UserManager<User> _userManager;
     public HomeController(UserManager<User> _userManager)
     {
         this._userManager = _userManager;
     }

     [HttpPost]
     public async Task<IActionResult> Login([FromForm] String userName, String password,bool remmberMe)
    {

            //.......
            var jwtAuthorizationManager = new JWTAuthorizationManager(_userManager );
            
            var loginResult = await jwtAuthorizationManager.Authenticate(userName, password);
    }
}

Upvotes: 0

Related Questions