0

Currently having an issue where I am trying to retrieve the name of the currently logged in user. My login method calls a token manager which builds the token and adds the appropriate claims. See below:

        [HttpPost]
        [Route("Login")]
        public async Task<IActionResult> Login([FromBody] TokenViewModel vm)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return BadRequest();
                }

                var user = await _userManager.FindByEmailAsync(vm.Email);
                var isLoginRequestValid = await _userManager.CheckPasswordAsync(user, vm.Password);

                if (!isLoginRequestValid)
                {
                    return BadRequest("Username or password is incorrect");
                }

                return Ok(new TokenViewModel { Token = _tokenManager.BuildJwtToken(vm.Email) });
            }
            catch(Exception ex)
            {
                return BadRequest(ex);
            }
        }

and token manager:

        public string BuildJwtToken(string email)
        {
            var claims = new[]
            {
                new Claim(JwtRegisteredClaimNames.Email, email),
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
            };

            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"]));

            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

            var token = new JwtSecurityToken(_config["Jwt:Issuer"],
                _config["Jwt:Audience"],
                claims,
                expires: DateTime.Now.AddMinutes(double.Parse(_config["Jwt:ExpireTime"])),
                signingCredentials: creds);

            return new JwtSecurityTokenHandler().WriteToken(token);
        }

I've reviewed quite a few posts regarding this issue and still am yet to find a solution. The authentication itself is working fine. Furthermore if I inspect User.Identity and exam it's claims at the time of the request, then I am able to see a claim that has the name (which is an email test@test.com in this case) in it. See screenshot below which shows the first claim is the email claim and contains a value of test@test.com however I'm unable to retrieve the Claims directly through User.Identity:

enter image description here

Why is my User.Identity.Name still null here despite having successfully added the claim?

GregH
  • 5,125
  • 8
  • 55
  • 109
  • I only see you're filling the emailaddress claim. you should fill the name claim: https://stackoverflow.com/questions/41830898/usejwtbearerauthentication-does-not-get-user-identity-name-populated/41831919#41831919 – jps Dec 12 '18 at 19:09
  • 1
    yep didn't see that post- this should be closed as a duplicate – GregH Dec 12 '18 at 19:12

1 Answers1

1

Looks like I needed to add the claim:

new Claim(ClaimTypes.Name, email)

as only using:

new Claim(JwtRegisteredClaimNames.Email, email)

does not hook up the claim to identity

This addition was in my BuildJwtToken(string email) method. Now everything is being hooked up properly. Hope this helps someone else in the future

GregH
  • 5,125
  • 8
  • 55
  • 109