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 /admin route?
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:

  1. Authenticate user
  2. Authorize action