Understanding JWT (JSON Web Token)
JSON Web Token (JWT) is an open standard (RFC 7519) that defines a compact and self-contained way for securely transmitting information between parties as a JSON object. It is primarily used for Authentication and Authorization in web applications.
1. How JWT Works in a Login Process
Unlike traditional session-based methods, JWT is Stateless, meaning the server doesn't need to store session data.
- Login Request: The user submits their credentials (ID/Password) to the server.
- Token Creation: Upon successful authentication, the server generates a JWT using a secret key.
- Token Delivery: The server sends the token back to the client (browser).
- Token Storage: The client stores the token in LocalStorage or a Cookie.
- Subsequent Requests: For every future request, the client includes the JWT in the HTTP Authorization header.
- Token Verification: The server verifies the token's signature. If valid, it processes the request for the authenticated user.
2. Structure of a JWT
A JWT consists of three parts separated by dots (.):
- Header: Specifies the token type (JWT) and the signing algorithm (e.g., HS256).
- Payload: Contains the "claims" or the data about the user (e.g., user ID, roles, expiration time).
- Signature: A hash created by taking the encoded header and payload, and signing it with a server-side secret key to ensure the token hasn't been tampered with.
3. Advantages of JWT
- Stateless: The server doesn't need to keep a session record in memory, allowing for better scalability and less resource consumption.
- Mobile Friendly: Much easier to implement in mobile applications compared to cookie-based sessions.
- CORS Support: Facilitates authentication across multiple domains or microservices.