Marin
Marin

Reputation: 931

Why can't I create a jwt token with SHA256?

I am implementing a JWT based authentication for the first time, and based my implementation on some resources I found online. I was wondering, my secret for the jwt is defined as:

"JwtConfig": {
    "secret": "pma_secret_2019_2020",
    "durationInMinutes": 1440,
    "issuer": "localhost:5001"
 }

Now I have a problem with this piece of code:

var symmetricKey = new SymmetricSecurityKey(
    Encoding.UTF8.GetBytes(_secret)
);
var signinCredentials =
    new SigningCredentials(symmetricKey, SecurityAlgorithms.Sha256);

var expirationDate = DateTime.Now.AddMinutes(_durationInMinutes);

var tokenDescriptor = new SecurityTokenDescriptor
{
    Subject = new ClaimsIdentity(claims),
    Expires = expirationDate,
    SigningCredentials = signinCredentials
};

var tokenHandler = new JwtSecurityTokenHandler();
var token = tokenHandler.CreateToken(tokenDescriptor);

The create Token throws the following exception:

System.NotSupportedException: IDX10634: Unable to create the SignatureProvider.
Algorithm: 'System.String', SecurityKey: 'Microsoft.IdentityModel.Tokens.SymmetricSecurityKey'
 is not supported.

Can someone explain why I keep getting this error? Is it related to the size of the secret or its characters or something else?

The code works when the algorithm is changed to HmacSHA256. But I want to understand why it doesn't work with SHA256.

Upvotes: 3

Views: 5802

Answers (2)

Ivan Kashtanov
Ivan Kashtanov

Reputation: 704

SHA256 is just a hashing algorithm, it doesn't provide signature mechanism. That's why HMAC is there in the right option.

Upvotes: 2

Arsalan Valoojerdi
Arsalan Valoojerdi

Reputation: 1026

Change SecurityAlgorithms.Sha256 to SecurityAlgorithms.HmacSha256Signature

Upvotes: 5

Related Questions