我在验证我获得的 JWT 令牌的签名时遇到了一些问题.令牌使用 HS256 签名.我尝试创建签名以证明收到的签名的代码是:
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.
JWT 的三个部分是 Base64Url 编码:
The three parts of a JWT are Base64Url encoded:
JWT 表示为 URL 安全部分的序列,由句点 ('.') 字符.每个部分都包含一个 base64url 编码的价值.
A JWT is represented as a sequence of URL-safe parts separated by period ('.') characters. Each part contains a base64url-encoded value.
但是您使用了 Base64 编码.Base64Url 使用 '-' 和 '_' 而不是 '+' 和 '/' 并且还省略了末尾的填充 '='.
But you used Base64 encoding. Base64Url uses '-' and '_' instead of '+' and '/' and also omits the padding '=' on the end.
这里是一个例子 如何在 C# 中将 base64 转换为 bas64url 编码
Here is an example how to convert the base64 to bas64url encoding in C#
这篇关于验证 JWT Token c# 的签名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!