Authentication & JWT
Implement secure authentication using JWT tokens, hashing passwords, and protecting routes.
0 of 5 concepts completed (0%)
What You'll Learn
Tutorial Contents
1.Password Hashing & Verification
const bcrypt = require("bcrypt");async function hashPassword(plaintext) { return bcrypt.hash(plaintext, SALT_ROUNDS); }
async function verifyPassword(plaintext, hash) { return bcrypt.compare(plaintext, hash); }
// Registration async function register(email, password) { if (password.length < 8) throw new Error("Password too short"); const existing = await db.user.findOne({ email }); if (existing) throw new Error("Email already registered"); const passwordHash = await hashPassword(password); return db.user.create({ email, passwordHash }); }
// Login constant-time comparison prevents timing attacks async function login(email, password) { const user = await db.user.findOne({ email }); const fakeHash = "$2b$12$invalid.hash.to.compare.against"; const isValid = user ? await bcrypt.compare(password, user.passwordHash) : await bcrypt.compare(password, fakeHash); if (!user || !isValid) throw new Error("Invalid credentials"); return user; } ```
2.JWT Access & Refresh Token Pattern
function generateAccessToken(user) { return jwt.sign( { userId: user.id, email: user.email, role: user.role }, process.env.JWT_ACCESS_SECRET, { expiresIn: "15m" } ); }
function generateRefreshToken(user) { return jwt.sign( { userId: user.id, tokenVersion: user.tokenVersion }, process.env.JWT_REFRESH_SECRET, { expiresIn: "7d" } ); }
// Refresh endpoint returns new access token app.post("/auth/refresh", async (req, res) => { const refreshToken = req.cookies.refreshToken; if (!refreshToken) return res.status(401).json({ error: "No refresh token" });
try { const payload = jwt.verify(refreshToken, process.env.JWT_REFRESH_SECRET); const user = await db.user.findById(payload.userId);
// Token version check allows revoking all tokens if (user.tokenVersion !== payload.tokenVersion) { return res.status(401).json({ error: "Token revoked" }); }
const accessToken = generateAccessToken(user); res.json({ accessToken }); } catch { res.status(401).json({ error: "Invalid refresh token" }); } }); ```
Code Example
const bcrypt = require("bcrypt");
const jwt = require("jsonwebtoken");
// Hash password
const hash = await bcrypt.hash(password, 10);
// Verify password
const valid = await bcrypt.compare(inputPassword, hash);
// Generate JWT
const token = jwt.sign(
{ userId: user.id, role: user.role },
process.env.JWT_SECRET,
{ expiresIn: "1h" }
);
// Middleware to protect routes
const authenticate = (req, res, next) => {
const token = req.headers.authorization?.split(" ")[1];
if (!token) return res.status(401).json({ error: "Unauthorized" });
const decoded = jwt.verify(token, process.env.JWT_SECRET);
req.user = decoded;
next();
};Pro Tips
- 1Use bcrypt with 10-12 rounds minimum. It's intentionally slow to make brute-force attacks impractical. Argon2id is the modern recommended alternative.
- 2Store refresh tokens in HttpOnly, Secure, SameSite=Strict cookies not localStorage. This prevents XSS attacks from stealing tokens.
- 3Always validate JWT signatures on EVERY protected request. Decode + verify are two different operations.
- 4Rate limit authentication endpoints: 5 attempts per 15 minutes. Without this, brute force attacks work in seconds.
Topics Covered
Continue Learning
Explore the official documentation and deepen your knowledge with real-world practice.
Explore the Full Portfolio
This is the complete portfolio of Sufi Khan Sulaiman, a technology leader specialising in B2B commerce and digital automation. Start from the Home page for the overview, then move through two decades of career experience across FLIR Systems, Lorex Technology, and 1c Platform, and the full catalogue of project case studies spanning headless commerce migrations, AI recommendation engines, and multi-channel fulfilment systems.
The skills and certifications page maps the technical and leadership capabilities behind the work, while the articles and the knowledge base break down the thinking into actionable frameworks. For hands-on learning, the tutorials and applications sections cover practical builds from front-end fundamentals to full-stack web apps.
For consulting engagement, the expertise page outlines service offerings, the ecommerce hub covers platform architecture and automation strategy, and the ecommerce guide (PDF) is a downloadable 55-page field manual. When you are ready to talk, the contact page is the direct line.