Authentication and Authorization are two different—but related—security processes in web applications.
✅ 1. Authentication (Who Are You?)
Authentication is the process of verifying a user's identity.
👉 It answers “Are you really the person you claim to be?”
Real-Time Examples:
- Logging in with email + password
- Logging in with Google / Facebook OAuth
- Entering OTP or fingerprint
- Scanning Face ID
How Authentication Works in Web Apps:
- User enters login details.
- Backend verifies the credentials.
- If valid → backend sends a token (JWT) or sets a session cookie.
- Client stores the token in:
- LocalStorage
- SessionStorage
- HttpOnly cookies (more secure)
🧪 Authentication Flow Example (JWT)
Client → sends login email/password
Server → validates
Server → returns JWT token
Client → stores token
Client → sends token in Authorization header for all protected APIs
🆓 2. Authorization (What Are You Allowed To Do?)
Authorization decides what actions the authenticated user can perform or which resources they can access.
👉 It answers “What can you do?”
Real-Time Examples:
- Admin can delete users
- User can view only their profile
- Guest cannot access dashboard
- Editor can create but not delete posts
Common Authorization Types:
- Role-based → admin, user, moderator
- Permission-based → create, update, delete
- Resource-based → access to a specific record
🔄 Authentication vs Authorization
| Feature | Authentication | Authorization |
|---|---|---|
| Meaning | Identity verification | Access control |
| Question Answered | Who are you? | What can you do? |
| Happens | First | After authentication |
| Stored as | Tokens, Cookies | Roles, Permissions |
| Example | Login | Admin privileges |
🔐 How They Work Together in Real Apps
Example: Accessing Admin Dashboard
- User logs in → authenticated
- Server checks user role → authorized
- If role = "admin" → allow
- Else → 403 Forbidden
⚙️ Real Example (JWT Authorization Middleware)
function authMiddleware(req, res, next) {
const token = req.headers.authorization?.split(" ")[1];
if (!token) return res.status(401).json({ message: "Not authenticated" });
try {
const user = jwt.verify(token, process.env.JWT_SECRET);
req.user = user;
next();
} catch {
res.status(403).json({ message: "Token invalid" });
}
}
Role Check:
function adminOnly(req, res, next) {
if (req.user.role !== "admin") {
return res.status(403).json({ message: "Not authorized" });
}
next();
}
🎯 In Short (Interview Summary):
Authentication = Verifying identity
✔ Login, OTP, Google OAuth
✔ Results in session or token
Authorization = Permission checking
✔ What user can access
✔ Based on roles or permissions
Both work together to protect routes and resources.