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
:
Why is my User.Identity.Name
still null here despite having successfully added the claim?