简体   繁体   中英

How to set ClaimsPrincipal.Identity.Name from Claim with custom type in ASP.NET Core WebApi

I use JWT Bearer to secure my WebApi endpoints. All works fine so far but I am wondering why the "Name" property of the ClaimsIdentity of the ClaimsPrincipal is null. I can remember somewhere to find the information, that this property is set from the content of a Claim of type "name" (correct???). I have a Claim of type "username" in my JWT that contains the username and I try to find a way to map that into the HttpContext.User.Identy.Name property.

Is there any configuration for that?

EDIT: The whole project is only for educational purposes, that is the reason for the quite simple code...

This is how I set the Claim :

private string GenerateJwtToken(User user)
{
    // generate token that is valid for 7 days
    var tokenHandler = new JwtSecurityTokenHandler();
    var key = Encoding.ASCII.GetBytes(_appSettings.JwtSecret);

    var claims = new List<Claim>
    {
        new("id", user.Id.ToString()),
        new("username", user.Username)
    };

    if (user.Username == "pbrause")
        claims.Add(new("weatherForecast", "true"));

    var tokenDescriptor = new SecurityTokenDescriptor
    {
        Subject = new ClaimsIdentity(claims),
        Expires = DateTime.UtcNow.AddDays(7),
        Issuer = "me",
        Audience = "you",
        SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature),
        IssuedAt = DateTime.UtcNow
    };

    var token = tokenHandler.CreateToken(tokenDescriptor);

    return tokenHandler.WriteToken(token);
}

I use ClaimTypes.Name as key and user.username as value to set the claim, Then i can get user name in HttpContext.User.Identy.Name .

 List<Claim> claims = new List<Claim>
    {
         new Claim(ClaimTypes.Name, user.UserName),
                        
         //..........
     };

Demo:

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM