JWT Authentication — Complete Guide
JWT Authentication — Complete Guide: free step-by-step lesson with examples, common mistakes, and interview tips — part of MEAN Stack Tutorial on Toolliyo Academy.
On this page
MEAN Stack Tutorial · Lesson 51 of 100
JWT Authentication
Stack ✓ → Projects
Projects · 2 — Apps · ~6 min · MEAN — Authentication & Security
What is this?
JWT authentication issues signed JSON Web Tokens after login so MeanVerse Angular sends Bearer tokens on API calls without server sessions.
Why should you care?
Stateless tokens scale horizontally across Express instances behind a load balancer.
See it live — copy this example
Paste into your MeanVerse project (Angular + Express + MongoDB), then run with ng serve / node / mongosh as noted.
import jwt from 'jsonwebtoken';
export function signAccessToken(user: { id: string; roles: string[] }) {
return jwt.sign(
{ sub: user.id, roles: user.roles },
process.env.JWT_SECRET!,
{ expiresIn: '15m', issuer: 'meanverse' }
);
}
export function verifyAccessToken(token: string) {
return jwt.verify(token, process.env.JWT_SECRET!) as { sub: string; roles: string[] };
}
// middleware
const payload = verifyAccessToken(token);
req.user = { id: payload.sub, roles: payload.roles };
What happened?
- sign embeds sub (user id) and roles with expiry.
- verify throws if tampered or expired.
- Middleware attaches user to req for downstream routes.
Practice next
- Add POST /auth/login returning { accessToken }.
- Store JWT_SECRET in env — long random string.
- Build auth middleware extracting Bearer header.
- Add aud claim for meanverse-web vs mobile app.
- Return expiresIn seconds for Angular timer refresh.
Remember
JWT = signed claims, not encrypted session. Short expiry limits stolen token window. Verify on every protected Express route.
Mobile + web clients
Same JWT validates Angular SPA and React Native app.
Outcome: Auth service issues one token format for all channels.
Interview prep for this lesson
Practice these questions aloud after reading—each links to a full structured answer.
Sign in to ask a question or upvote helpful answers.
No questions yet — be the first to ask!