


Blog Details
HomeUnderstanding JWT (JSON Web Token)
Understanding JWT (JSON Web Token)
In today’s web development landscape, security and authentication are paramount. One popular method for securely transmitting information between parties is through JWT (JSON Web Token). It's compact, self-contained, and widely used for stateless authentication in modern applications, especially with REST APIs.
What is a JWT Token?
JWT (JSON Web Token) is an open standard (RFC 7519) that defines a compact and self-contained way for securely transmitting information as a JSON object between parties. This information can be verified and trusted because it is digitally signed.
🔍 Structure of a JWT
A JWT has three parts, separated by dots (.):
xxxxx.yyyyy.zzzzz
-
Header: Contains metadata like type and signing algorithm.
-
Payload: Contains the claims (user data, metadata, etc.).
-
Signature: Used to verify the token's integrity.
// Header
{
"alg": "HS256",
"typ": "JWT"
}
// Payload
{
"userId": 123,
"username": "devsingh",
"role": "admin",
"exp": 1712345678
}
// Signature
HMACSHA256(
base64UrlEncode(header) + "." + base64UrlEncode(payload),
secret
)
How JWT Works
-
✅ User Logs In
User provides credentials. If correct, the server generates a JWT and sends it back. -
🔐 Client Stores Token
The JWT is stored on the client-side (usually inlocalStorageorsessionStorage). -
📲 Send Token with Requests
The client sends the token in theAuthorizationheader:
Authorization: Bearer <token>
🔍 Server Verifies Token
The server verifies the token signature and checks expiry before granting access.
🚫 Common Mistakes to Avoid
-
❌ Never store JWT in cookies without
HttpOnlyandSecureflags. -
❌ Never expose secret keys to the frontend.
-
⛔ Avoid putting sensitive data like passwords inside the JWT payload.
🛡️ Refresh Tokens
JWTs are usually short-lived (e.g., 15 minutes). For persistent login:
-
Issue a refresh token (longer expiry).
-
On JWT expiry, use refresh token to get a new JWT.
-
Store refresh token securely, preferably in
HttpOnlycookies.
📦 Libraries & Tools
-
Node.js:
jsonwebtoken -
Python:
PyJWT -
Java:
jjwt,auth0-java -
.NET:
System.IdentityModel.Tokens.Jwt -
Laravel:
tymon/jwt-auth
🔗 https://jwt.io — Visual debugger and documentation
📘 RFC 7519: JSON Web Token (JWT)
