Search code examples
c#azurejwtazure-active-directoryadal

How to generate JWT Token with IdentityModel Extensions for .NET 5


I am using IdentityModel Extensions for .NET version 4 to generate JWT token with symmetric key and SHA256 as below and it works perfectly:

var tokenDescriptor = new SecurityTokenDescriptor
{
    Subject = new ClaimsIdentity(claims),

    TokenIssuerName = Issuer,
    AppliesToAddress = Audience,

    Lifetime = new Lifetime(now, expirationTime),

    SigningCredentials = new SigningCredentials(
        new InMemorySymmetricSecurityKey(symmetricKey),
        "http://www.w3.org/2001/04/xmldsig-more#hmac-sha256",
        "http://www.w3.org/2001/04/xmlenc#sha256"),
};

var securityToken = tokenHandler.CreateToken(tokenDescriptor);
var token = tokenHandler.WriteToken(securitytoken);

But when I tried to upgrade to IdentityModel Extensions for .NET 5 as below code:

var tokenDescriptor = new SecurityTokenDescriptor
{
    Subject = new ClaimsIdentity(claims),

    Issuer = Issuer,
    Audience = Audience,

    Expires = expirationTime,
    SigningCredentials = new SigningCredentials(
        new SymmetricSecurityKey(symmetricKey), "SHA256")
};

var securityToken = tokenHandler.CreateToken(tokenDescriptor);
var token = tokenHandler.WriteToken(stoken);

I got exception:

IDX10634: Unable to create the SignatureProvider.

SignatureAlgorithm: 'SHA256', SecurityKey: 'Microsoft.IdentityModel.Tokens.SymmetricSecurityKey' is not supported.

What's wrong with the new code using version 5.


Solution

  • They've changed their implementation a little bit, so

    change

    SigningCredentials = new SigningCredentials(
        new SymmetricSecurityKey(symmetricKey), "SHA256")
    

    to

    SigningCredentials = new SigningCredentials(
        new SymmetricSecurityKey(symmetricKey), Microsoft.IdentityModel.Tokens.SecurityAlgorithms.HmacSha256Signature)