問題描述
我在驗證我獲得的 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模板網!