flyingpig
flyingpig

Reputation: 622

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!

Upvotes: 16

Views: 16529

Answers (4)

Aravindh Kumar
Aravindh Kumar

Reputation: 56

For those who are looking for RSA (asymmetric keys), You can set the key id while constructing the security credentials (below snippet shows an example).

var accessTokenDescription = new SecurityTokenDescriptor
{
    Issuer = "https://example.in",
    IssuedAt = DateTime.UtcNow,
    NotBefore = DateTime.UtcNow,
    Expires = DateTime.UtcNow.AddSeconds(accessTokenExpiry),
    SigningCredentials = new SigningCredentials(new RsaSecurityKey(rsa)
    {
        KeyId = "hello-world"
    }, SecurityAlgorithms.RsaSsaPssSha256)
};

When the token is generated, it will have kid in the JWT header like below:

Decoded JWT showing the kid in header

Upvotes: 0

Dirnei
Dirnei

Reputation: 169

Here is a small copy and paste ready function you could use:

private static string CreateJwt(IEnumerable<Claim> claims, DateTime expiresAt)
    {
        // Creating the symmetric key and signing credentials
        var veryUnsecureSecureString = "YOURSYMMETRICKEYHERE";
        var symmetricKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(veryUnsecureSecureString));
        symmetricKey.KeyId = "YourKeyId";
        var credentials = new SigningCredentials(symmetricKey, SecurityAlgorithms.HmacSha256);

        // Set security token descriptor
        var tokenDescriptor = new SecurityTokenDescriptor {
            Subject = new ClaimsIdentity(claims),
            Expires = expiresAt,
            Issuer = "your issuer",
            Audience = "your audience",
            SigningCredentials = credentials,
        };

        // Crate jwt security token handler to create the token
        var tokenHandler = new JwtSecurityTokenHandler();

        // create the jwt object
        var token = tokenHandler.CreateToken(tokenDescriptor);

        // convert to string
        return tokenHandler.WriteToken(token);
    }

Here is a generated JWT:

eyJhbGciOiJIUzI1NiIsImtpZCI6IllvdXJLZXlJZCIsInR5cCI6IkpXVCJ9.eyJuYmYiOjE2MTE2ODQ2NzgsImV4cCI6MTYxMTg0NjY3MywiaWF0IjoxNjExNjg0Njc4LCJpc3MiOiJ5b3VyIGlzc3VlciIsImF1ZCI6InlvdXIgYXVkaWVuY2UifQ.wHOw-PkrP1iXgLkcT0JznDr2D01KAdFpVkdL6xIo5zc

Decoded with JWT.io debugger i get the following:

Header:

{
  "alg": "HS256",
  "kid": "YourKeyId",
  "typ": "JWT"
}

Payload:

{
  "nbf": 1611684678,
  "exp": 1611846673,
  "iat": 1611684678,
  "iss": "your issuer",
  "aud": "your audience"
}

Upvotes: 4

John Burrows
John Burrows

Reputation: 121

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);

Upvotes: 10

aterno
aterno

Reputation: 31

Try this:

var securityKey = new SymmetricSecurityKey(Encoding.Default.GetBytes(secretKey));
securityKey.KeyId = "KID_HERE";
var signingCredentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256Signature);

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

jwtSecurityToken.Header.Add("kid", requestAPIKey);

Upvotes: 3

Related Questions