I’m trying to access the user Id from the token but everything I try returns null. The generated token has the necessary information so I don’t think it’s the token generation.
This is the part creates the token
var tokenHandler = new JwtSecurityTokenHandler();
var key = Encoding.ASCII.GetBytes(_jwtSettings.Secret);
var tokenDescriptor = new SecurityTokenDescriptor()
{
Subject = new ClaimsIdentity(new[]
{
new Claim(JwtRegisteredClaimNames.Sub, user.Email),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
new Claim(JwtRegisteredClaimNames.Email, user.Email),
new Claim(ClaimTypes.NameIdentifier, existingAppUser.Id),
new Claim("id", existingAppUser.Id),
}),
Expires = DateTime.UtcNow.AddDays(7),
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
};
var token = tokenHandler.CreateToken(tokenDescriptor);
return new AuthenticationResult()
{
Token = tokenHandler.WriteToken(token)
};
When I decode the generated token I can see all of the claims in the token but I can’t access it on the project.
This is the part trying to access the name identifier or the id claims
var claimsList = _httpContextAccessor.HttpContext.User.Claims.ToList();
var identityName = _httpContextAccessor.HttpContext.User.Identity.Name;
var nameId = _httpContextAccessor.HttpContext.User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
var id = _httpContextAccessor.HttpContext.User.FindFirst(x => x.Type == "id")?.Value;
This is the JWT Configuration from Startup
services.AddAuthentication(x =>
{
x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
x.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(x =>
{
x.SaveToken = true;
x.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
{
ValidateIssuerSigningKey = false,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(jwtSettings.Secret)),
ValidateAudience = false,
ValidateLifetime = true,
ValidateIssuer = false
};
});
services.AddAuthorization();
services.AddHttpContextAccessor();
This is the class I’m trying to access it from
public class CurrentUserService : ICurrentUserService
{
private readonly IHttpContextAccessor _httpContextAccessor;
public CurrentUserService( IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
}
public string UserId { get => _httpContextAccessor.HttpContext.User.Claims.Single(x => x.Type == "id").Value; }
public string GetUserId()
{
var claimsList = _httpContextAccessor.HttpContext.User.Claims.ToList();
var identityName = _httpContextAccessor.HttpContext.User.Identity.Name;
var nameId = _httpContextAccessor.HttpContext.User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
var id = _httpContextAccessor.HttpContext.User.FindFirst(x => x.Type == "id")?.Value;
return "123";
}
}
I don’t know what I am missing here. How do I get the userId from the token?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
Well It turns out I forgot to put
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
in the necessary controllers.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0