Amend to previous – Jwt token mapping

When I write entries on this site I do my best to fully research and solve issues I encounter in a meaningful way in line with maintainability and cleanliness. Occasionally, I am not as successful in this endeavor as I would like – as was the case with how I referenced the the User Id from Auth0 in my previous entry: here

In this post, I expressed frustration at the lack of mapping for, what I believe are, common values that are part of the Jwt standard which meant a certain amount of digging and kludgy code to extract the needed value. I was wrong.

This evening, while researching something else, I stumbled across the proper way to achieve what I was looking for. It turns out, you can get it to work with a simple definition in the Startup.cs class when you configure the JwtBearer – see below:

services.AddAuthentication(options =>
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options =>
options.Authority = Configuration["Auth0:Domain"];
options.Audience = Configuration["Auth0:Audience"];
options.SaveToken = true;
options.TokenValidationParameters = new TokenValidationParameters
NameClaimType = ClaimTypes.NameIdentifier

view raw


hosted with ❤ by GitHub

You can see on line 11 what I mean. By doing this, you can change the controller code to the following:

public async Task<IActionResult> Get()
var rng = new Random();
var data = Enumerable.Range(1, 5).Select(index => new WeatherForecast
Date = DateTime.Now.AddDays(index),
TemperatureC = rng.Next(20, 55),
Summary = Summaries[rng.Next(Summaries.Length)]
return Ok(new {
WeatherMan = (await _userService.GetUserAsync(this.User.Identity.Name)).FullName,
Data = data

view raw


hosted with ❤ by GitHub

Now, instead of casting and digging into the claims to perform matching, we can let .NET Core do it for us and simply use the .Name property on the resolved identity.

Neat, eh. This makes the code much cleaner and more straightforward.


2 thoughts on “Amend to previous – Jwt token mapping

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s