Understanding JWT (JSON Web Token) and How It Works
JSON Web Token (JWT) is a compact, URL-safe method for securely transmitting information between parties as a JSON object. JWTs are commonly used for authentication and information exchange, ensuring integrity and authenticity.
What is JWT?
A JWT consists of three parts:
- Header
- Payload
- Signature
These are encoded in Base64Url and separated by dots (.):
1. Header
The header typically consists of two parts:
alg– the signing algorithm (e.g., HS256)typ– the token type (JWT)
Example:
2. Payload
The payload contains the claims. Claims are statements about an entity (usually the user) and additional metadata. There are three types of claims:
- Registered claims: Predefined, e.g.,
iss(issuer),exp(expiration),sub(subject) - Public claims: Custom claims with public names
- Private claims: Custom claims agreed upon between parties
Example:
3. Signature
To create the signature:
The signature ensures that the token wasn’t altered.
How JWT Works
- User logs in with credentials.
- Server validates the credentials.
- Server generates a JWT with a secret key.
- JWT is sent to the client.
- Client stores the JWT (localStorage, sessionStorage, or cookie).
- Client sends the JWT with each subsequent request (usually in the
Authorizationheader). - Server validates the token to allow access to protected resources.
JWT Flow Diagram
Implementing JWT in Node.js (Example)
We will use Express.js and jsonwebtoken package.
Install Dependencies
Example Code
How It Works
- Login: Client sends credentials to
/login. - Generate Token: Server generates JWT if credentials are valid.
- Send Token: Token is sent back to client.
- Send Requests: Client includes token in
Authorizationheader. - Verify Token: Server checks token validity for protected routes.
Benefits of JWT
- Stateless Authentication: No need to store session info on the server.
- Compact & Portable: Can be sent via URL, headers, or cookies.
- Secure: Can be signed and optionally encrypted.
- Cross-platform: Works in web, mobile, and desktop apps.
Conclusion
JWT provides a secure and scalable way to handle authentication in modern web applications. It is widely used in REST APIs, SPAs, and mobile apps due to its stateless nature and simplicity.
