How to get the user identifier in an ASP.NET Core API?

How would I go about getting the user_id of the authenticated user of my application in ASP.NET Core? More specifically I’m using it as a Web API.

When you use the API authorization features to obtain an access token to call your own API on behalf of a given end-user the user_id is included in the access token in the sub claim.

You then configure your API in accordance to the associated quickstart:

var options = new JwtBearerOptions
{
    Audience = Configuration"Auth0:ApiIdentifier"],
    Authority = $"https://{Configuration"Auth0:Domain"]}/"
};
app.UseJwtBearerAuthentication(options);

When you do the above and include the [Authorize] attribute in a given route the information contained in the received access token will be mapped to a claims principal that you can access at your route method through the use of this.User.

By default the JWT authentication handler in .NET will map the sub claim of a JWT access token to the System.Security.Claims.ClaimTypes.NameIdentifier claim type, which means that in order to access the user identifier you can do the following:

Debug.WriteLine($"UserId: {this.User.FindFirst(ClaimTypes.NameIdentifier).Value}");

If you want to map the sub JWT claim to a different claim you can do so by configuring the claim type mapping of the JWT security handler, something like:

JwtSecurityTokenHandler.DefaultInboundClaimTypeMap[JwtRegisteredClaimNames.Sub] = ClaimTypes.Upn;

With the above configuration the user identifier would now be available in the Upn claim type instead of the default NameIdentifier.

1 Like