Auth2 min read
Authentication vs Authorization
Two terms everyone confuses. Here's the difference and how to implement both
S
Shahar Amir
The Difference
Authentication = Who are you? Authorization = What can you do?
javascript
123456
// Authentication: verify identityconst user = await verifyToken(token);// user = { id: 1, email: "shahar@example.com" }
// Authorization: check permissionsconst canEdit = user.role === 'admin';Authentication Methods
javascript
12345678910
// 1. JWT Tokenconst token = jwt.sign({ userId: 1 }, SECRET, { expiresIn: '1h' });
// 2. Sessionreq.session.userId = user.id;
// 3. API Keyif (req.headers['x-api-key'] !== API_KEY) { return res.status(401).json({ error: 'Unauthorized' });}Authorization Patterns
Role-Based (RBAC)
javascript
1234567891011121314
const roles = { admin: ['read', 'write', 'delete'], editor: ['read', 'write'], viewer: ['read']};
function canDo(user, action) { return roles[user.role]?.includes(action);}
// Usageif (!canDo(user, 'delete')) { return res.status(403).json({ error: 'Forbidden' });}Permission-Based
javascript
12345678910111213
// More granular than rolesconst user = { id: 1, permissions: ['posts:read', 'posts:write', 'users:read']};
function hasPermission(user, permission) { return user.permissions.includes(permission);}
if (!hasPermission(user, 'posts:delete')) { throw new Error('Forbidden');}Middleware Example
javascript
1234567891011121314151617181920212223242526272829303132
// Auth middlewarefunction authenticate(req, res, next) { const token = req.headers.authorization?.split(' ')[1]; if (!token) { return res.status(401).json({ error: 'No token' }); } try { req.user = jwt.verify(token, SECRET); next(); } catch { res.status(401).json({ error: 'Invalid token' }); }}
// Authorization middlewarefunction authorize(...roles) { return (req, res, next) => { if (!roles.includes(req.user.role)) { return res.status(403).json({ error: 'Forbidden' }); } next(); };}
// Usageapp.delete('/posts/:id', authenticate, authorize('admin', 'editor'), deletePost);Quick Reference
| Code | Meaning | When |
|---|---|---|
| 401 | Unauthorized | Not logged in |
| 403 | Forbidden | Logged in, no permission |
#auth#security#fundamentals#patterns
Stay Updated 📬
Get the latest tips and tutorials delivered to your inbox. No spam, unsubscribe anytime.