验证JWT令牌c#的签名 [英] verify signature of JWT Token c#

查看:142
本文介绍了验证JWT令牌c#的签名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在验证获得的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的三个部分是

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令牌c#的签名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆