Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add kid to jwt header using SecurityTokenDescriptor in .netcore

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!

like image 596
flyingpig Avatar asked Oct 27 '18 00:10

flyingpig


People also ask

How do I add a child to my JWT token?

In JwtSecurityToken, I was adding it with this code: jwtSecurityToken. Header. Add("kid", requestAPIKey);

What is kid in JWT header?

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.


1 Answers

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);
like image 101
John Burrows Avatar answered Sep 22 '22 12:09

John Burrows