What is JWT
JSON Web Token (JWT) is an open standard (RFC 7519) that defines a compact and self-contained way for securely transmitting information between parties as a JSON object. This information can be verified and trusted because it is digitally signed. JWTs can be signed using a secret (with the HMAC algorithm) or a public/private key pair using RSA or ECDSA.
Make JWT more safe
secret for every Account
In some best practice of JWT, they just say we need an universe secret for every account signature, which mostly from an envirment varible. But the secret is so fundemental, is it enough safe that a global secret for all account? Nobody care it, nobody discuss it, nobody mention it.
We use different salt to hash account password for different account, why we use same secret for all account? The JWT is JUST as important as user’s password!
In my opinion, we should use different secret for every account, just like password salt.
If we use different secret for every account, we should save the secret in server side, DB or redis. Of course, this will slow down the JWT validate flow, but we could save the secret in server’s memory cache after server start up.
save & validate signature in server side
JWT is mostly about how to verify the JWT token is valid, by the signature. In most scene, this is great. But in some case, for example, we want kick off a special user, JWT can do nothing.
So, we could save the JWT signature in the server, then we could verify the JWT twice:
- first, verify the signature;
- second, check the signature in server DB or redis, if exists, the JWT is valid; or else invalid
By this method, we can kick off user or force user re-login.
Also, there are some tricks, we don’t need to save all JWT payload in the server, for example, we can just save the userId and JWT signature in the server side.
JWT for anonymous or visitors
Sometime we want give better user expirence for the anonymous or visitors, we can use JWT to record visitor’s information. For example, the user’s information:
name
IP address
first visit time
location(optional)
use these information, we could track visitors and provide good expirence.
Question
If we use JWT this way, why we use JWT instead of session? One of the most benefit of JWT is the client can get many information from JWT, even they have not connect to the server.