Read JWT token claims in ASP.Net Core

In an Blazor app I've been working on to teach myself the technology I wanted to read claims that were sent from my API site but do so via the JWT authentication token that was provided. It turns out, .NET Core has plumbing that makes this task simple.

In this example, I'm going to assume there is a claim for a user id.

C# (Client side Blazor)

var jwt = new JwtSecurityTokenHandler().ReadJwtToken(token);
string user = jwt.Claims.First(c => c.Type == "user").Value;

For reference, to create this token the API site could would look something like this:

C# (Server side)

var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("Your secret key value"));
var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);

var permClaims = new List<Claim>();
permClaims.Add(new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()));
permClaims.Add(new Claim("user", "some_username"));

//Create Security Token object by giving required parameters    
var token = new JwtSecurityToken("",
									expires: DateTime.Now.AddDays(1),
									signingCredentials: credentials);
var jwtToken = new JwtSecurityTokenHandler().WriteToken(token);

Leave a comment

Please note that we won't show your email to others, or use it for sending unwanted emails. We will only use it to render your Gravatar image and to validate you as a real person.