Shahriar Morshed
Shahriar Morshed

Reputation: 112

How do I get the user info for whom the jwt token was issued?

I have created a token based authentication in my asp.net core application .When I post with the proper login model , it gives me the token. Now I want to to know how I can Get the info of the user for which this token is generated . This is the code to create the token. Let me know if I can help with any other information.

if (ModelState.IsValid)
{
    var user = await _userManager.FindByNameAsync(model.UserName);
    if (user != null)
    {
         var result = await _signInManager.CheckPasswordSignInAsync(user, model.Password, false);
         if (result.Succeeded)
         {
            var claims = new List<Claim>()
            {
                new Claim(JwtRegisteredClaimNames.Sub,user.Email),
                new Claim(JwtRegisteredClaimNames.Jti,Guid.NewGuid().ToString()),
                new Claim(JwtRegisteredClaimNames.UniqueName,user.UserName)
            };
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Tokens:key"]));
            var cred = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

            var token = new JwtSecurityToken(
                                _config["Tokens:Issuer"],
                                _config["Tokens:Audience"],
                                claims,
                                expires: DateTime.UtcNow.AddMinutes(20),
                                signingCredentials: cred );    
            var results = new
            {
                token = new JwtSecurityTokenHandler().WriteToken(token),
                                expiration = token.ValidTo
            };
            return Created("", results);
        }
    }
}
return BadRequest();

Upvotes: 0

Views: 1310

Answers (2)

Shahriar Morshed
Shahriar Morshed

Reputation: 112

After some searching, I have found a solution . You can get the user info from the token

[HttpGet]
        public IActionResult GetUser([FromHeader]string token)
        {

            var stream = token;
            var handler = new JwtSecurityTokenHandler();
            var jsonToken = handler.ReadToken(stream);
            var tokenS = handler.ReadToken(stream) as JwtSecurityToken;
            var jti = tokenS.Claims.First(claim => claim.Type == "sub").Value;
            return Created("", jti);
        }

Upvotes: 0

Farhad Zamani
Farhad Zamani

Reputation: 5861

You can get user information by ClaimsIdentity like this

var userIdentity = (User.Identity as ClaimsIdentity);

string userName = userIdentity.FindFirst(JwtRegisteredClaimNames.UniqueName).Value;
string email = userIdentity.FindFirst(JwtRegisteredClaimNames.Sub).Value;
string guid = userIdentity.FindFirst(JwtRegisteredClaimNames.Jti).Value;

then change the var claims = new [] to var claims = new List<Claim>()

Or register the IHttpContextAccessor in DI and get it from Constructor to access the HttpContext.User

var claimsIdentity = _contextAccessor.HttpContext.User.Identity as ClaimsIdentity;
var userName = claimsIdentity?.FindFirst(JwtRegisteredClaimNames.UniqueName);

This link maybe helpful for you

Upvotes: 2

Related Questions