ShaharAmir
← Back to Blog
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 identity
const user = await verifyToken(token);
// user = { id: 1, email: "shahar@example.com" }
// Authorization: check permissions
const canEdit = user.role === 'admin';

Authentication Methods

javascript
12345678910
// 1. JWT Token
const token = jwt.sign({ userId: 1 }, SECRET, { expiresIn: '1h' });
// 2. Session
req.session.userId = user.id;
// 3. API Key
if (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);
}
// Usage
if (!canDo(user, 'delete')) {
return res.status(403).json({ error: 'Forbidden' });
}

Permission-Based

javascript
12345678910111213
// More granular than roles
const 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 middleware
function 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 middleware
function authorize(...roles) {
return (req, res, next) => {
if (!roles.includes(req.user.role)) {
return res.status(403).json({ error: 'Forbidden' });
}
next();
};
}
// Usage
app.delete('/posts/:id',
authenticate,
authorize('admin', 'editor'),
deletePost
);

Quick Reference

CodeMeaningWhen
401UnauthorizedNot logged in
403ForbiddenLogged in, no permission
401 = "Who are you?" (auth failed) 403 = "I know you, but no" (authz failed)

#auth#security#fundamentals#patterns

Stay Updated 📬

Get the latest tips and tutorials delivered to your inbox. No spam, unsubscribe anytime.