2

This is my code for token generation:

var claims = new List<Claim>
{
    new Claim(ClaimTypes.NameIdentifier, appUser.Id.ToString()),
    new Claim(ClaimTypes.Name, appUser.UserName)
};

var roles = await _userManager.GetRolesAsync(user);

foreach (var role in roles)
{
    claims.Add(new Claim(ClaimTypes.Role, role));
}

var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config.GetSection("AppSettings:Token").Value));

var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha512Signature);

string issuer = _config["Token:Issuer"];

var jwtSecurityToken = new JwtSecurityToken(
    issuer: issuer,
    audience:issuer,
    claims: claims,
    expires: DateTime.Now.AddMinutes(5),
    signingCredentials: new SigningCredentials(key, SecurityAlgorithms.HmacSha256)
);

jwtSecurityToken.Header.Add("kid", requestAPIKey);
var token = new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken);

The token outputs this:

{
  "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier": "7",
  "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name": "ligeros",
  "exp": 1540619440,
  "iss": "http://localhost:5000",
  "aud": "http://localhost:5000"
}

How can I make it to output this instead?

{
  "nameid": "7",
  "unique_name": "ligeros",
  "nbf": 1540613190,
  "exp": 1540703190,
  "iat": 1540613190
}

I don't care about nbf, exp and iat. I just want the urls to be removed and become nameid, unique_name, instead of http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier and http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name . Thank, you!

Matt Ke
  • 3,599
  • 12
  • 30
  • 49
flyingpig
  • 602
  • 1
  • 8
  • 19
  • Does this answer your question? [Get short claim type name](https://stackoverflow.com/questions/36315559/get-short-claim-type-name) – Jesse Jun 15 '21 at 07:42

2 Answers2

4

I fixed it:

var claims = new List<Claim>
{
    new Claim("nameid", appUser.Id.ToString()),
    new Claim("unique_name", appUser.UserName)
};

var roles = await _userManager.GetRolesAsync(user);

foreach (var role in roles)
{
    claims.Add(new Claim("roles", role));
}
Matt Ke
  • 3,599
  • 12
  • 30
  • 49
flyingpig
  • 602
  • 1
  • 8
  • 19
0

İf you still dont find it. You should use jwtsecuritytokenhandler.createjwttoken() method. İnstead of using New jwtsecuritytoken. For more information and details, check my questions.

Atakan Günay
  • 27
  • 1
  • 3