ASP.NET Core, JWT Tokens, and the User.Identity.Name property - A Discovery
I've been working on creating a token-based auth system and I wanted to write about a discovery that I made. I've been following the excellent ASP.NET Core Token Authentication Guide.
I was able to get everything up and running as suggested in the guide, but when I accessed the User.Identity.Name property, it was null. I was hoping to find the Name of the user there, but it wasn't. After some exploration, I was able to determine the solution. You simply add the following code in Startup.cs. I added this to the TokenValidationParameters area as outlined in the Guide.
var tokenValidationParameters = new TokenValidationParameters
{
// Ensure that User.Identity.Name is set correctly after login
NameClaimType = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier",
... Existing code here ...
};
If you want to use a different claim as your User.Identity.Name, then use that claim name instead of the XmlSoap schema above. We're actually not using username, we're using an Id number that identifies the user.