May 30, 2017

Overriding the NameClaimType when using the ASP.NET Core OpenID Connect middleware

When using the ASP.NET Core OpenID Connect middleware, after a user has signed in you can access the name of the user by using the User.Identity.Name property. What this does under the cover is to look for the claim type and then return that value.

In the case of Auth0, we actually return a user’s name in the name claim of an id_token and this does not get automatically mapped to the claim type. So previously in our ASP.NET Core Quickstart I actually wrote a whole bunch of code demonstrating how to handle the OnTicketReceived event to read the name claim, and use that value to add a claim of the type to ensure that everything works correctly.

Turns out there is a much easier way as a user pointed out to me.

All you need to do is to specify the NameClaimType of the TokenValidationParameters property of the OpenIdConnectOptions. So in the case of an Auth0 id_token, you need to specify the NameClaimType with a value of name:

var options = new OpenIdConnectOptions("Auth0")
    // .. some code omitted for brevity ..

    // Set the correct name claim type
    TokenValidationParameters = new TokenValidationParameters
        NameClaimType = "name"

Now, every time you get the user’s name through the User.Identity.Name property, it will look for the value of the name claim on the user, and return the correct value for the user’s name.

Follow me on Twitter @jerriepelser for tweets about coding and building a Saas.