JSON Web Token (JWT) advantages/disadvantages over Cookies
Advantages
JWT
is a stateless authentication mechanism as the user state is never saved in the database. As JWTs are self-contained, all the necessary information is there, reducing the need of going back and forward to the database. With JWT we don't need to query database to authenticate the user for every api call.- Protects against
CSRF
(Cross Site Request Forgery) attacks. - JWT is compact. Because of its size, it can be sent through an URL, POST parameter, or inside an HTTP header.
- You can authorize only the requests you wish to authorize. Cookies are sent for every single request.
- You can send JWT to any domain. This is especially useful for single page applications that are consuming multiple services that are requiring authorization - so I can have a web app on the domain
myapp.com
that can make authorized client-side requests tomyservice1.com
and tomyservice2.com
. Cookies are bound to a single domain. A cookie created on the domainfoo.com
can't be read by the domainbar.com
.
Disadvantages
- Not easy to revoke a
JWT
as it is a stateless authentication mechanism. It makes difficult to implement feature likeSign out from all devices
. This is easy to implement using session based authentication as we just need to delete the session from database. - Need to write some code to implement whereas
cookies
work out of the box.
a lot of web-related info can be found in a similar post here: Token Authentication vs. Cookies; I would like to call out some "architectural" differences:
- JWTs are a standardized container format to encode user and client related information in a secure way using "claims" (whereas cookie contents and signing/encryption are not standardized)
- JWTs are not restricted to present session-like information about the authenticated user itself; they can also be used to delegate access to clients that act on behalf of the user
- JWTs allow for a more granular access model than cookies because JWTs can be limited in "scope" (what they allow the client to do) as well as time