Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JWT Header algorithm: is "hs256" the same as "http://www.w3.org/2001/04/xmldsig-more#hmac-sha256"

Tags:

c#

.net

jwt

I'm trying to sign a JWT using HS256. I'm using System.IdentityModel.Tokens.Jwt . When decoding the token using jwt.io I get invalid signature and I've noticed that my headers read:

{
  "alg": "http://www.w3.org/2001/04/xmldsig-more#hmac-sha256",
  "typ": "JWT"
}

rather than {"alg":"HS256","typ":"JWT"} as I expected.

Is this what's causing the invalid signature? Also any ideas on a fix? Please note that I need to include custom claims as well.

var securityKey = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(Encoding.UTF8.GetBytes(clientsecret));
var credentials = new Microsoft.IdentityModel.Tokens.SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256Signature);
var header = new JwtHeader(credentials);
like image 806
Kadament Avatar asked Feb 02 '26 01:02

Kadament


2 Answers

SecurityAlgorithms.HmacSha256Signature

change

SecurityAlgorithms.HmacSha256

like image 175
Bugra Onucyildiz Avatar answered Feb 04 '26 16:02

Bugra Onucyildiz


You can create your JSON Web Token (JWT) as follows using System.IdentityModel.Tokens.Jwt, which should set all fields correctly (secret is the key you use to sign your JWT):

var now = DateTime.UtcNow;
var tokenDescriptor = new SecurityTokenDescriptor
{
  Subject = new ClaimsIdentity(new[] { new Claim("sub", "customer") }),
  Issuer = "Who issued the token",
  Claims = new Dictionary<string, object>
  {
    ["email"] = Email, 
  },
  IssuedAt = now,
  NotBefore = now,
  Expires = now + TimeSpan.FromDays(1),
  SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(secret), SecurityAlgorithms.HmacSha256Signature)
};
var tokenHandler = new JwtSecurityTokenHandler();
var token = tokenHandler.CreateToken(tokenDescriptor);
var serializedToken = tokenHandler.WriteToken(token);

serializedToken finally contains the serialized JWT.

Please note that the SecurityTokenDescriptorclass is from the Microsoft.IdentityModel.Tokens namespace of the same NuGet package, not from System.IdentityModel.Tokens namespace.

like image 26
ckuri Avatar answered Feb 04 '26 16:02

ckuri



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!