JSON Web Token (JWT) is a way to generate auth tokens. It’s is an open standard (RFC 7519) that defines a simple way for securely transmitting information between client and server as a JSON object.
JWT Tokens V/S Cookies
Since HTTP is a stateless protocol, after you login (via username/password, OAuth 2 etc), for every future request to the server, you need to keep telling the server that you have already logged in so it can allow you to perform authenticated/authorized actions. One way to do this is via “session” cookies and other way is to use “auth” tokens.
JWT offers many benefits over using session cookies but the 2 major ones are:
- Server doesn’t need to ask DB to know who the user is because the user info is embedded inside the token itself! #performance!
- It works the same for both native mobile apps and browser clients. i.e. servers don’t need to implement two different mechanisms (browser v/s native).
Learn more: 10 things you should know about tokens and cookies
Note: You can click on the picture to zoom and read
Note: I’ll be using the same blog-post Redux app in here as well.
Live App: https://protected-escarpment-79486.herokuapp.com
Source Code: https://github.com/rajaraodv/react-redux-blog
What Does A JWT Token look like?
The token has 3 parts: <header>.<payload>.<signature>
- Header: A JSON(Base64 encoded) that has info about algorithm used(like HS256, RSA) and so on.
- Payload: A JSON(Base64 encoded) that has info about the user.
- Signature: A String that was generated using #1 + #2 + “a secret” (that only the server knows), using the algorithm mentioned in #1.
Below is the picture from https://jwt.io that shows the JWT token used in our blog app in both encoded and decoded manners.