JWT Explained | What Is JWT ? How JWT Works? JWT VS Session | JSON Web Token | JWT (Hindi/Urdu)
Table of Contents
Introduction
This tutorial explains JSON Web Tokens (JWT), a compact and self-contained way for securely transmitting information between parties as a JSON object. We'll cover what JWT is, how it works, and its advantages over traditional session-based authentication. This guide is useful for developers looking to implement authentication in web applications using JWT.
Step 1: Understand What JWT Is
- JWT stands for JSON Web Token.
- It is a standard for securely transmitting information as a JSON object.
- JWTs can be signed (to ensure authenticity) and optionally encrypted (to ensure confidentiality).
Step 2: Structure of a JWT
A JWT is composed of three parts:
-
Header
- Contains metadata about the token, including the type (JWT) and signing algorithm (e.g., HMAC SHA256).
- Example of a header:
{ "alg": "HS256", "typ": "JWT" }
-
Payload
- Contains claims or statements about the user and additional data. Claims can be registered, public, or private.
- Example of a payload:
{ "sub": "1234567890", "name": "John Doe", "admin": true }
-
Signature
- Created by taking the encoded header, the encoded payload, a secret, and signing it using the algorithm specified in the header.
- Example:
HMACSHA256( base64UrlEncode(header) + "." + base64UrlEncode(payload), secret)
Step 3: How JWT Works
-
User Authentication
- A user logs in with their credentials.
- Server validates credentials and generates a JWT.
-
Token Transmission
- The server sends the JWT to the client.
- The client stores the JWT (usually in local storage or cookies).
-
Token Usage
- For subsequent requests, the client sends the JWT in the HTTP Authorization header:
Authorization: Bearer <token>
- For subsequent requests, the client sends the JWT in the HTTP Authorization header:
-
Verification
- The server verifies the JWT by checking the signature and claims before allowing access to protected resources.
Step 4: Benefits of Using JWT
- Stateless Authentication: The server does not need to store session information, making it easier to scale applications.
- Cross-Domain Authentication: JWTs can be used across different domains or servers.
- Compact Size: JWTs are compact and can be easily sent via URL, POST parameters, or HTTP headers.
Step 5: JWT vs Session-Based Authentication
- Session-Based:
- Server stores session data.
- Requires server-side memory, which can be a bottleneck.
- JWT:
- No server memory required for sessions.
- Tokens are self-contained and contain all necessary information.
Conclusion
JWTs are a powerful tool for managing authentication in modern web applications. They provide a stateless, compact, and versatile method for securely transmitting user information. As a next step, consider implementing JWT in a sample project to gain hands-on experience with its capabilities.