简体   繁体   English

验证Jwt的正确方法

[英]Correct way to verify Jwt

I have written this code here我在这里写了这段代码

 jwt.verify(token.split(':')[1], 'testTest')

And i am trying verify this so it can return true and move on.我正在尝试验证这一点,以便它可以返回 true 并继续。 The point the jwt is coming as a payload example jwt 将作为有效负载示例出现

How can i verify this jwt so我怎样才能验证这个 jwt

`token.split(':')[1] can match testTest`

jwt.verify does not do that. jwt.verify不会这样做。 It verifies the jwt with the secret or public key.它使用秘密或公钥验证 jwt。 If you don't want to verify it and just get the payload, what you want to do is decode the jwt, then retrieve the value and do string comparison.如果您不想验证它而只想获取有效负载,那么您要做的是解码 jwt,然后检索值并进行字符串比较。

let decoded = jwt.decode(token);
if(decoded.sub == "testTest")
{
    //Do your stuff...
}

You can read more about jwt in their github page您可以在他们的github 页面中阅读有关 jwt 的更多信息

My approach is to keep the verify method to only verify that the token hasn't been modified:我的方法是保持 verify 方法只验证令牌没有被修改:

jwt.verify(token, JWT_SECRET);

And use the decode method to get the payload:并使用decode方法获取有效载荷:

const payload = jwt.decode(token, JWT_SECRET);

After that you can check your payload value之后,您可以检查您的有效载荷值

first important question - who is the token issuer?第一个重要问题 - 谁是代币发行者?

And do you want to verify the token validity AND / OR just compare the content of the token to a given value?您是否想验证令牌有效性和/或只是将令牌的内容与给定值进行比较?

verification (& decoding) is done with验证(和解码)是用

var decoded = jwt.verify(token, '<public key for verification>');

if(decoded.sub == "<value to match>"){
// TODO: implement match case
}

(assuming you are using jsonwebtoken package) (假设您使用的是 jsonwebtoken 包)

You have to provide the public key for verification which is given by the token issuer.您必须提供由令牌发行者提供的用于验证的公钥。

If you want to test it properly, I propose to generate a token on jwt.io -> you can generate upfront a private/public key pair on your own and use it for encoding and verification before decoding.如果您想正确测试它,我建议在 jwt.io 上生成一个令牌 -> 您可以自己预先生成一个私钥/公钥对,并在解码前将其用于编码和验证。

It is also possible to just decode the token, but without the verification against the public key given by the issuer, anybody could send you tokens which will be quite unsave on your side.也可以只对令牌进行解码,但如果没有针对发行者提供的公钥进行验证,任何人都可以向您发送令牌,而这些令牌对您来说将是非常不安全的。

Best wishes最好的祝愿

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM