How To Implement Authentication with JWT: A Step-by-Step Guide
JSON Web Tokens (JWT) offer a stateless, secure way to handle user authentication in modern web apps. Instead of storing sessions on the server, you issue a signed token that the client sends with every request. This tutorial walks you through the core steps — from issuing a token to verifying it on protected routes.
Before diving in, ensure your backend environment supports JWT (e.g., Node.js with jsonwebtoken or Python with PyJWT). You’ll also need a secret key stored securely in environment variables.
1. Generate a JWT on User Login
When a user logs in with valid credentials, create a token containing essential payload data (like user ID or role). Use a strong secret key and set an expiration time to limit the token’s lifespan.
- Payload: Include only non‑sensitive fields (e.g.,
{ "userId": 123, "role": "admin" }). - Signing: Use HS256 or RS256 algorithm — HS256 is simpler for single‑server apps.
- Expiration: Set
expclaim (e.g., 15 minutes for access tokens).
2. Send the Token to the Client
Return the JWT in the HTTP response body or in an Authorization header (the body approach works well for SPAs). Instruct the client to store it securely — typically in an HTTP‑only cookie for best protection against XSS.
- Option A:
res.json({ token })— the client then attaches it manually. - Option B: Set a cookie with
httpOnly,sameSite: 'strict', andsecureflags.
3. Verify the JWT on Protected Routes
Create middleware that extracts the token from the request (header or cookie), verifies its signature and expiration, and attaches the decoded payload to the request object. If verification fails, respond with 401 Unauthorized.
- Extraction: Read from
Authorization: Bearer <token>or fromreq.cookies. - Verification: Use
jwt.verify(token, secret)— it throws an error if invalid or expired. - Payload use: Set
req.user = decodedso downstream handlers know the user.
4. Refresh and Revoke Tokens
Short‑lived access tokens reduce risk. Implement a refresh token (longer lifetime, stored securely) that allows the client to obtain a new access token without re‑logging. For revocation, maintain a blacklist of invalidated JWTs or use short expiration times.
- Refresh flow: Send a separate
/refreshendpoint that validates the refresh token and issues a new access token. - Revocation: Keep a server‑side list of revoked token IDs (jti) or rely on short
exptimes.
Conclusion
Implementing JWT authentication is straightforward: generate tokens at login, send them to the client, verify them on every protected request. Combine short access tokens with refresh tokens to balance security and user experience. Always use HTTPS and store secrets and tokens securely.