What is JWT ?
A good question to start with. JWT stands for JSON Web Tokens. JSON Web Tokens are an open, industry standard RFC 7519 method for representing claims securely between two parties.
JWT is basically used for authentication purpose. JWT Token is issued / generated by server. The token contains JSON payload which identifies user. This token can be used by client applications to communicate with APIs (by sending it along an HTTP Request as an HTTP header) so that APIs can identify user and take appropriate action.
How does JWT look like ?
JWT is divided into three parts:
- Header: It stores the hash algorithm and token type
- Payload: It stores actual data you want to share about user
- Signature: It contains HMACSHA256 hash of header, payload and secret key. This prevents from alteration of JWT.
It looks like this when serialized. Three parts are separated by dot
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9. eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ. XbPfbIHMI6arZ3Y922BhjWgQzWXcXNrz0ogtVhfEd2o
After decoding you can see Header, payload and signature as below. Decoded using jwt.io
JWT in nutshell
Here is a diagram illustrating basic flow of jwt authentication in client-server architecture system.
- Send login request.
- Generate JWT depending on user authentication credentials.
- Sign JWT & send back to client.
- For processing other microservices, send JWT in HTTP header.
- Verify whether JWT received is from legitimate source using signature.
- Read payload available in JWT.
- Process your business logic.
- Done 🎉
Once client app receives JWT it is very important to store JWT securely. So that it can't be read by any third party. You should store the JWT in memory for secure storage.
Lifetime of JWT
JWT authorizes user to perform actions, But if JWT is leaked any third party to perform actions on behalf of authenticated user. To prevent this JWT expiry time should not be greater than 15 minutes. App should request new JWT before current JWT expires.
What if JWT from memory is gone ?
Right. When user closes app data from memory is removed. This will logout user asking user to login each time after app starts. This is not ideal scenario, generally you want user to be logged in. To achieve this you need to use refresh tokens.
I will talk about refresh tokens in next article. Stay Tuned!
Did you find this article valuable?
Support Akash Pate by becoming a sponsor. Any amount is appreciated!