问题
I have some problems to verify the signature of a JWT token I get. The token is signed with HS256. The code where I try to create a signature to proof the received one is:
JwtSecurityToken token = tokenHandler.ReadJwtToken(tokenString);
byte[] keyBytes = Encoding.UTF8.GetBytes("secret");
HMACSHA256 hmac = new HMACSHA256(keyBytes);
byte[] signatureBytes = hmac.ComputeHash(Encoding.UTF8.GetBytes(token.RawHeader + "." + token.RawPayload));
string signature = Convert.ToBase64String(signatureBytes);
The signature I get from the received token is for example:
pYscLlinuNhO-sFyEIRRLZP7yrl8GopGJ3I6QSxg2tU
But the signature I get from my algorithm is in this case:
pYscLlinuNhO+sFyEIRRLZP7yrl8GopGJ3I6QSxg2tU=
So the signatures are close, but not equal. I don't get what I'm doing wrong at the verification of the signature. Letters and numbers seems to be correct every time but special characters are mostly different and there is always a '=' at the end of the signature. Maybe someone knows what I'm doing wrong.
回答1:
The three parts of a JWT are Base64Url encoded:
A JWT is represented as a sequence of URL-safe parts separated by period ('.') characters. Each part contains a base64url-encoded value.
But you used Base64 encoding. Base64Url uses '-' and '_' instead of '+' and '/' and also omits the padding '=' on the end.
Here is an example how to convert the base64 to bas64url encoding in C#
来源:https://stackoverflow.com/questions/63597137/verify-signature-of-jwt-token-c-sharp