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.
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.
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
)
β
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 in localStorage or sessionStorage).
π² Send Token with Requests
The client sends the token in the Authorization header:
Authorization: Bearer <token>
π Server Verifies Token
The server verifies the token signature and checks expiry before granting access.
β Never store JWT in cookies without HttpOnly and Secure flags.
β Never expose secret keys to the frontend.
β Avoid putting sensitive data like passwords inside the JWT payload.
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 HttpOnly cookies.
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)