简体   繁体   中英

Token inside JWT payload

Is it a good idea to have a random generated token inside the JWT payload and check is with the database on each request?

I've done my reseach on JWT and how it actually works, and I know its main purpose is to avoid querying the database on each request to authorize the user, but I still have to do it as I need certain information about the user who is making the request.

I also need a good solution to immediately revoke a token if I need to. Blacklisting the token seems like a good solution intially, but that would require extra requests and I don't think it's worth the effort.

So the solution I came up with is to generate a random token and save that token in my database and also put it in the JWT payload. That way when a user makes a new request, it first checks if the JWT token is valid and if it is, it then checks if the token associated in the payload is valid.

So if a user needs to change his password for example, his token would change and all JWT tokens with the previous token in their payload would fail to validate.

So the solution would be like this:

When the user registers, it is assigned with a randomToken and also stored inside the payload. If registration is successful, the server returns the jwtToken generated.

var jwtToken = jwt.sign({token: randomToken}, PRIVATE_KEY, SIGN_OPTIONS);

So when a user makes a new request, it first checks if the JWT token is valid.

var legit = jwt.verify(token, JWT_PUBLIC_KEY, SIGN_OPTIONS);

If it is, it the proceeds to checking the token inside the payload with the user token in the database.

SELECT * FROM users WHERE token = legit.token

If everything is correct, it then proceeds with the normal request.

'Is it a good idea...' is not a very good way to ask a question, but I will try to answer it...

1. JWT is secure

The reason behind the private key is to make sure the user does not change the token. Therefore, it's totally secure to store an object that is used often in the token, and there is no need to store the token anywhere. The signed object would look like this:

{
  expirationDate: 1560530063664,
  ...user data
}

2. Blacklisting and Revoking Tokens

To blacklist a certain token I believe the best way is the way you came up with. Depending on how many users you have accessing the website simultaneously, it might be possible/a good idea to just use an array thigh.

Although it may be nice to have the ability to blacklist a token, is it really necessary? If the user updates their password, do they really need to be logged out? If you still think you need a token store I believe there are multiple npm packages to do so...

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