JSON Web Tokens (JWT)
JSON Web Token (JWT) is an open standard that defines a compact and self-contained way for securely transmitting information between parties as a JSON object.
This information can be verified and trusted because it is digitally signed. JWTs can be signed using a secret hashed with the HMAC algorithm or via a public/private key pair using RSA.
JWT: The 3 Keys
JSON Web Tokens consist of three parts separated by dots .
which are:
- Header: Contains information of type of token and the hashing algorithm that has been used.
- Payload: The body of the token. Even though this information is encoded using base64 it is still available to the public and anyone can decode and read it. Do not store sensitive information such as passwords or secrets.
- Signature: Used to verify the authenticity of the token. The client or server knows the secret to verify the token is authentic and hasn't been modified. It contains base64 of the header and payload. Then it hashes it using (HS256, RS512, ES384, etc...) together with a secret only known to server/client. Finally, it gets base64 encoded.
The signature of a JWT contains the previous two blocks. That ensures any modification to the header or payload is going to invalidate the token during the validation process.
JWT: Client to Server Flow
JWT can be used to transmit any type of information, but they are the perfect tool when dealing with authentication credentials. We can take a front-end application and a server side API scenario to illustrate an example:
- A user logs in with its credentials. The Front-End application sends a token request to the server.
- The backend validates the credentials and generates a JWT token accordant to the user details and permissions.
- The API response contains the JWT in plain text or an error if credentials are invalid.
- The front-end extracts the information on the token and stores it for future usage. Saving tokens on cookies of local storage allows for persistent user sessions.
- Whenever the user performs actions on the front-end, request to the backend are going to be signed using the JWT.
- When server receives a request it analyses the JWT and determinates if user is authenticated and authorised to perform the action.
The following illustration is taken from the Tech CBT channel on Youtube. I highly recommend checking out their video showing an introduction to JWT.
References