I am trying to use JWT
for authentication mechanism in ASP.NET Core Web API
project. Suppose this project has not MVC
part and does no
in your claims (second code snippet) I can only see this:
new Claim(ClaimTypes.NameIdentifier, applicationUser.UserName),
but you need to add this:
new Claim(ClaimTypes.Name, applicationUser.UserName),
then User.Identity.Name should contain the username.
Another option is to set the namespace for the JwtRegisteredClaimNames.Sub
in the tokenValidationParameters
. This will let you continue to use the standard:
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 ...
}
Update: Diogo Barros left a comment on my blog about this topic:
"Hello,
Thank you for your help. This worked for me. For more consistency and safety, you can use the ClaimTypes.NameIdentifier (in the System.Security.Claims namespace), instead of the hardcoded string."
I've changed our code to use the built-in ClaimTypes enumeration as it is a bit more elegant than using the namespace string.