What are JSON Web Tokens? Can it really be used to replace traditional session cookies? This article is a note made while studying JWT.
What is JSON Web Tokens
JSON Web Token is abbreviated as JWT, pronounced as jot, and is an IETF standard [RFC 7519], which defines the Simple and safe way to exchange information. The information is packaged in a JSON Object, that is how it gets the name. This information can be verified as trusted content because it is digitally signed. The method can be single ciphertext (HMAC) or public key private key system (RSA).
How to use JSON Web Tokens
After the user logs in with the server, the server can return a JSON Web Token, which can be stored in the browser’s local storage or cookie.
When users want to access some information that requires authentication again, they need to send this JWT back to the server, usually in the form of an Authorization header, for example:
Authorization: Bearer <token>
This method is lighter than the session cookie method for the server, because the server does not need to keep relevant session information(stateless), only the information in the JWT to confirm whether the user can access the relevant resources.
The Benefit of Using JSON Web Tokens
- Easily achieve horizontal scaling
- Easier to maintain (no need for long term storage)
- Cross domain RESTful API (without CORS cookies)
- Can control the expiration of the tokens
- Single token contains all authencation information
After the user is authenticated, the server returns a session ID, which can then be used to inquire user information.
- Need a shared database to store session information
- Cannot easily logout user
Potential Problems of JSON Web Token
- XSS, CSRF, Replay attack, MITM
- The size of JWT is much larger than a simple session ID
- It becomes very important to protect the ciphertext or private key used for the signature.
How to Deal with Replay Attacks
- Use short expiration time
- Client side refreshs token frequently
- Server side maintains a list to block malicious clients
The Benefit of Storing JWT or Session ID in Cookies
Don’t use JWT for persistent, long-lived data.