Get JWT claims directly from the token, ASP Net Core 2.1
Here is a simple workaround:
var tokenDescriptor = new SecurityTokenDescriptor
{
Expires = DateTime.UtcNow.AddHours(3),
Subject = new ClaimsIdentity(new[]
{
new Claim(ClaimTypes.Name, "[email protected]"),
new Claim(ClaimTypes.Email, "[email protected]")
}),
SigningCredentials = new SigningCredentials(key: new SymmetricSecurityKey(key), algorithm: SecurityAlgorithms.HmacSha256Signature)
};
var Securitytoken = new JwtSecurityTokenHandler().CreateToken(tokenDescriptor);
var tokenstring = new JwtSecurityTokenHandler().WriteToken(Securitytoken);
var token = new JwtSecurityTokenHandler().ReadJwtToken(tokenstring);
var claim = token.Claims.First(c => c.Type == "email").Value;
return claim;
For example in my current project I get claims by validation. Its refresh token, so I cant use [Authorize] attribute.
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
public ClaimsPrincipal ValidateRefreshToken(string refreshToken)
{
try
{
var validationParams = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(tokenSecurityKey),
ValidateLifetime = true
};
return new JwtSecurityTokenHandler().ValidateToken
(
refreshToken,
validationParams,
out SecurityToken token
);
}
catch (Exception e)
{
Log.Error(e.Message);
return null;
}
}
and then
var claims = ValidateRefreshToken(refreshToken);
...
var userIdString = claims.Claims.FirstOrDefault(x => x.Type == "userId")?.Value;