简体   繁体   中英

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. The point the jwt is coming as a payload example

How can i verify this jwt so

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

jwt.verify does not do that. It verifies the jwt with the secret or public key. 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.

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

You can read more about jwt in their github page

My approach is to keep the verify method to only verify that the token hasn't been modified:

jwt.verify(token, JWT_SECRET);

And use the decode method to get the payload:

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)

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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