Authentication vs Authorization
Authentication - who are you?
Verifying the identity of a user.
text
User provides: email + password / OAuth token / biometric
System verifies: yes, this is AliceAuthorization - what can you do?
Verifying what an authenticated user is allowed to access.
text
Alice is authenticated.
Can Alice delete this post? -> check role/permissions -> yes/noCommon implementations
Session-based auth
text
1. User logs in -> server creates session -> stores in DB
2. Server sends session ID in cookie (httpOnly)
3. Every request: browser sends cookie -> server looks up sessionJWT (JSON Web Token)
text
1. User logs in -> server creates signed JWT
2. Client stores token (memory or httpOnly cookie)
3. Every request: client sends JWT -> server verifies signature
JWT structure: header.payload.signature
payload: { userId, role, exp: timestamp }ts
// JWT verification
import jwt from 'jsonwebtoken';
function authMiddleware(req, res, next) {
const token = req.headers.authorization?.split(' ')[1];
if (!token) return res.status(401).json({ error: 'Unauthorized' });
try {
const payload = jwt.verify(token, process.env.JWT_SECRET);
req.user = payload;
next();
} catch {
res.status(401).json({ error: 'Invalid token' });
}
}Role-based authorization (RBAC)
ts
function requireRole(role: string) {
return (req, res, next) => {
if (req.user.role !== role) {
return res.status(403).json({ error: 'Forbidden' });
}
next();
};
}
router.delete('/posts/:id', authMiddleware, requireRole('admin'), deletePost);| Authentication | Authorization | |
|---|---|---|
| Question | Who are you? | What can you do? |
| HTTP status on failure | 401 Unauthorized | 403 Forbidden |
| Happens | First | After authentication |
401 means "I don't know who you are" - log in first. 403 means "I know who you are, but you can't do this".
updated
did you know it?