0
0
Expressframework~5 mins

Why authorization differs from authentication in Express

Choose your learning style9 modes available
Introduction

Authentication checks who you are. Authorization checks what you can do. They are different steps to keep apps safe.

When a user logs in to prove their identity.
When deciding if a user can access a page or feature.
When protecting sensitive data from unauthorized users.
When giving different permissions to different user roles.
When building secure APIs that require user validation and permission checks.
Syntax
Express
app.use(authenticate);
app.use(authorize);

Authentication usually happens before authorization.

Middleware functions in Express help separate these concerns clearly.

Examples
This middleware checks if the user sent a valid token to prove who they are.
Express
function authenticate(req, res, next) {
  // Check user identity
  if (req.headers.authorization === 'valid-token') {
    req.user = { id: 1, role: 'admin' };
    next();
  } else {
    res.status(401).send('Not authenticated');
  }
}
This middleware checks if the authenticated user has permission to access the resource.
Express
function authorize(req, res, next) {
  // Check user permission
  if (req.user.role === 'admin') {
    next();
  } else {
    res.status(403).send('Not authorized');
  }
}
Sample Program

This example shows how Express middleware first checks if the user is authenticated, then if they are authorized to access the admin page.

Express
import express from 'express';
const app = express();

function authenticate(req, res, next) {
  if (req.headers.authorization === 'valid-token') {
    req.user = { id: 1, role: 'admin' };
    next();
  } else {
    res.status(401).send('Not authenticated');
  }
}

function authorize(req, res, next) {
  if (req.user.role === 'admin') {
    next();
  } else {
    res.status(403).send('Not authorized');
  }
}

app.use(authenticate);
app.get('/admin', authorize, (req, res) => {
  res.send('Welcome Admin');
});

// Simulate a request with valid token
const req = { headers: { authorization: 'valid-token' } };
const res = {
  status(code) { this.statusCode = code; return this; },
  send(message) { this.message = message; }
};

let nextCalled = false;
function next() { nextCalled = true; }

// Run authenticate
authenticate(req, res, () => {
  // Run authorize
  authorize(req, res, () => {
    res.send('Welcome Admin');
  });
});

console.log(res.message || res.statusCode);
OutputSuccess
Important Notes

Authentication confirms identity; authorization controls access.

Always authenticate before authorizing in your app flow.

Use clear error codes: 401 for authentication failure, 403 for authorization failure.

Summary

Authentication means checking who the user is.

Authorization means checking what the user can do.

Both are important for app security but serve different purposes.