A JSON web token(JWT) is JSON Object which is used to securely transfer information over the web (between two parties). It can be used for an authentication system and can also be used for information exchange.
Structure of JSON Web Token (JWT): JSON Web Tokens consist of three parts separated by dots (.) which are:
- Header: Contains signature algorithm name used to sign the payload
- Payload: Contains user attributes
- Signature: Signature value of the payload
In authentication, when the user successfully logs in using their credentials, a JSON Web Token will be returned and must be saved locally (typically in local or session storage, but cookies can also be used), instead of the traditional approach of creating a session in the server and returning a cookie.
Whenever the user wants to access a protected route or resource, the user agent should send the JWT, typically in the Authorization header using the Bearer schema. The content of the header might look like the following:
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
This is a stateless authentication mechanism as the user state is never saved in server memory. The server’s protected routes will check for a valid JWT in the Authorization header, and if it is present, the user will be allowed to access protected resources.
As JWTs are self-contained, all the necessary information is there, reducing the need to query the database multiple times.