Authenticate VS Authorize - paulip114/blog GitHub Wiki
π AUTHENTICATION vs AUTHORIZATION
| Aspect | Authentication | Authorization | 
|---|---|---|
| What it means | Proving who you are | Checking what youβre allowed to do | 
| Question | "Who are you?" | "Can you access this?" | 
| Example | Logging in with email + password | Can access /adminroute? | 
| When it happens | First (login or identity check) | After authentication | 
| Involves | Passwords, tokens, biometric, etc. | Roles, permissions, resource ownership | 
| Response code | 401 Unauthorized | 403 Forbidden | 
π§ͺ Example:
GET /admin-dashboard
πΉ Step 1: Authentication
- Server checks: βDo you have a valid token or session?β
- β If not: 401 Unauthorized
πΉ Step 2: Authorization
- Server checks: βAre you an admin?β
- β If not: 403 Forbidden
π In Practice: Express.js Example
// middleware/authenticate.js
function authenticate(req, res, next) {
  const token = req.headers.authorization?.split(' ')[1];
  if (!token) return res.status(401).json({ message: 'Not logged in' });
  try {
    req.user = jwt.verify(token, secret);
    next(); // user is authenticated
  } catch {
    res.status(401).json({ message: 'Invalid token' });
  }
}
// middleware/authorize.js
function authorize(role) {
  return (req, res, next) => {
    if (req.user.role !== role) {
      return res.status(403).json({ message: 'Access denied' });
    }
    next(); // user is authorized
  };
}
app.get('/admin', authenticate, authorize('admin'), (req, res) => {
  res.send('Welcome Admin!');
});
β Summary
- Authentication = "Are you who you say you are?"
- Authorization = "Do you have permission to do this?"
They usually go hand in hand:
- Authenticate user
- Authorize action