SledgeHammer SledgeHammer - 2 months ago 23
C# Question

Get username in Asp.Net Core Controller

What is the accepted way to get the username of a Asp.Net Core REST service inside of the controller? Assuming the authentication is done by JWT?

I see

User.Claims.First().Value
contains the username, but is it always going to be in the first claim?

Or is there some better way to access it?

Answer

You can use the FindFirst() function on the ClaimsPrincipal class.

Examples:

// using built in claim types
User.FindFirst(System.Security.Claims.ClaimTypes.NameIdentifier); 

// using custom claim type
User.FindFirst("username");
Comments