UseJwtBearerAuthentication does not get User.Identity.Name populated

后端 未结 2 760
南方客
南方客 2020-12-18 18:19

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

相关标签:
2条回答
  • 2020-12-18 18:50

    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.

    0 讨论(0)
  • 2020-12-18 18:55

    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.

    0 讨论(0)
提交回复
热议问题