I am using .netcore 2 with JwtSecurityToken to generate a token
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);
Now because I use Idenity I have switched from JwtSecurityToken to Security Token Descriptor and my code is:
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(claims),
Expires = DateTime.Now.AddDays(1),
SigningCredentials = creds
};
My question is how can I add kid to my token header when using Security Token Descriptor? In JwtSecurityToken, I was adding it with this code:
jwtSecurityToken.Header.Add("kid", requestAPIKey);
How can I do the same thing with SecurityTokenDescriptor? Thank, you!
In JwtSecurityToken, I was adding it with this code: jwtSecurityToken. Header. Add("kid", requestAPIKey);
Key Id mainly refers to a Secret that can be retrieved and used to validate the signed JWT. - Mostly it is just a random guid that is stored as a secret Id. It should be provided by the generator of the JWT so that a Validator can retrieve the correct secret based on the "kid" to validate the signed JWT token.
Here's a code snippet I've used:
var tokenHandler = new JwtSecurityTokenHandler();
var key = Encoding.UTF8.GetBytes("Secret");
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(new Claim[]
{
new Claim(ClaimTypes.Name, UserId),
new Claim(name, value),
new Claim(name, value)
}),
Expires = DateTime.UtcNow.AddMinutes(5),
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
};
var token = tokenHandler.CreateJwtSecurityToken(tokenDescriptor);
token.Header.Add("kid", "");
token.Payload.Remove("iss");
token.Payload.Add("iss", "your issuer");
var tokenString = tokenHandler.WriteToken(token);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With