JWTs versus Sessions
Why are sessions not such a good thing? Well, there are three key reasons:
- Data is stored in plain text on the server.
Even though the data is usually not stored in a public folder, anyone with sufficient access to the server can read the contents of session files. - They involve filesystem read/write requests.
Every time a session starts or its data is modified, the server needs to update the session file. The same goes for every time the application sends a session cookie. If you have a large number of users, you can end up with a slow server unless you use alternative session storage options, such as Memcached and Redis. - Distributed/Clustered applications.
Since session files are, by default, stored on the file system, it’s hard to have a distributed or clustered infrastructure for high availability applications — ones that require the use of technologies such as load balancers and clustered servers. Other storage media and special configurations have to be implemented — and be done so in full awareness of their implications.
JWTs have many advantages over API keys, including:
- API keys are random strings, whereas JWTs contain information and metadata. This information and metadata can describe a wide range of things, such as a user’s identity, authorization data, and the validity of the token within a time frame or in relation to a domain.
- JWTs don’t require a centralized issuing or revoking authority.
- JWTs are OAUTH2 compatible.
- JWT data can be inspected.
- JWTs have expiration controls.
- JWTs are intended for space-constrained environments, such as HTTP Authorization headers.
- Data is transmitted in JavaScript Object Notation format (JSON).
- JWTs are represented using Base64url encoding