~3 hours Intermediate JWT · bcrypt · Sessions · Cookies
Overview
Authentication is the cornerstone of secure applications. This tutorial
covers the two primary authentication methods: JWT (stateless) and sessions
(stateful). You'll learn to hash passwords with bcrypt, generate and verify
JWTs, and manage user sessions with cookies.
Why this matters:
Protecting user data is critical. Understanding authentication ensures
your applications are secure and user identities are verified.
1. Authentication vs Authorization
Authentication: Verifying who a user is (login).
Authorization: Determining what a user can do (permissions).
Common flows: Login → Validate credentials → Return token/session → Use
token/session for subsequent requests.
// Authentication flow
// 1. User submits credentials (email + password)
// 2. Server validates credentials
// 3. Server creates a session or JWT
// 4. Client includes session cookie or JWT in requests
// 5. Server validates the session or JWT on each request
2. Password Hashing with bcrypt
Never store passwords in plain text. Use bcrypt to hash passwords securely.
npm install bcrypt
const bcrypt = require('bcrypt');
const saltRounds = 10;
// Hash a password
async function hashPassword(plainPassword) {
const hash = await bcrypt.hash(plainPassword, saltRounds);
return hash;
}
// Compare a password with a hash
async function comparePassword(plainPassword, hashedPassword) {
const match = await bcrypt.compare(plainPassword, hashedPassword);
return match; // true if match, false otherwise
}
// Example usage in registration
const hashed = await hashPassword('userpassword123');
// Store hashed in database
// Example usage in login
const isValid = await comparePassword('userpassword123', storedHash);
if (isValid) {
// Password matches, generate token/session
}
3. JSON Web Tokens (JWT)
JWT is a compact, URL‑safe token format used for stateless authentication.
Extend the Task Manager API with JWT authentication. Add registration and
login endpoints. Protect the task CRUD endpoints so that only authenticated users can access
them. Use the user ID from the JWT to associate tasks with users.
Sample outline
Register: POST /api/register – stores user with hashed
password.
Login: POST /api/login – returns JWT.
Middleware: authenticate(req, res, next) – verifies JWT and
attaches user.
Routes: All task routes use authenticate middleware.
Data: Each task has a `userId` field.
Mini‑Project
Authenticated Task Manager
Build a complete authenticated Task Manager API:
User registration and login with JWT
Tasks are associated with users
Protected endpoints for creating, reading, updating, and deleting tasks
User can only access their own tasks
Use bcrypt for password hashing
Add a logout endpoint (client-side token discard)
Sample outline
Users: id, email, name, passwordHash.
Tasks: id, title, description, completed, userId.
Auth: bcrypt for hashing, JWT for tokens.
Middleware: authenticate extracts user from token.
Routes: GET /tasks, POST /tasks, PUT /tasks/:id, DELETE
/tasks/:id (all protected).
Tutorial Summary
You learned authentication fundamentals: password hashing with bcrypt,
JWT generation and verification, and session management. You also
compared JWT and sessions to understand when to use each approach.
Key takeaway: Authentication is critical for security.
Always hash passwords, use secure tokens, and choose the right strategy
for your application.