Should I store the JWT token as a key and corresponding user info as value in Redis so that I can fetch info by token if valid
or
should I encode the user data in JWT itself and use Redis only for storing valid tokens?
Should I store the JWT token as a key and corresponding user info as value in Redis so that I can fetch info by token if valid
or
should I encode the user data in JWT itself and use Redis only for storing valid tokens?
2
Answers
The all idea of JWT is that won’t need to access the DB (or Redis) on every call and the user access data will be encoded in the token.
Saying that, the biggest drawback of JWT it that you can’t actively cancel or de-validate tokens, and the only way to do is by checking a black list of tokens on every user call, which kinda miss the purpose of not accessing the DB on every call.
A good compromise, in case you need a way to actively cancel tokens, is to use a fast validation method which for example can be based on Bloom Filter, and for that you might want to use RedisBloom.
Since @Guy Korland has already covered the basic idea of JWTs, I’ll comment on the two approaches you have mentioned.
This approach is not very helpful if all you’re trying to lookup from Redis is the user’s information. This is because the user information can directly be stored as
claims
in thepayload
section of JWT thereby avoiding the call to lookup from Redis. If theclaim
contains sensitive information, one can always encrypt the JWT token to ensure it’s not being accessed by un-intended recipients.That being said, the downside to not having to hit the cache at all is that you cannot invalidate/refresh the tokens. In general, it’s recommended that you do not have long lived tokens as it’s a security vulnerability.
This is better than the previous option and it works if the user’s information is encoded as part of the JWT token. Also, you can store the ‘context’ of the token as the value in Redis (key being the JWT itself). The ‘context’ here means the last time the token was used (lastAccessTime), expiry interval, etc. Using this ‘context’ you can determine whether the session is active/inactive and whether to invalidate the token and provide a fresh token to the client.