Authentication vs Authorization
Identity & Access

Authentication vs Authorization

Understand the key differences between Authentication (AuthN) and Authorization (AuthZ): analogies, HTTP status codes, and implementation patterns.

Because Authentication and Authorization both start with 'Auth' and both deal with security access, people often mix them up or use them as if they mean the same thing. However, they represent two completely different steps in security: • Authentication (AuthN) asks: 'Who are you, and can you prove it?' • Authorization (AuthZ) asks: 'What are you allowed to do?' Authentication always comes first. A system must know who you are before it can decide what you are allowed to see or do. Understanding this distinction is essential for designing secure APIs and avoiding critical access control bugs.

Definition

Authentication (AuthN) is the process of verifying a user's identity, while Authorization (AuthZ) is the process of determining what permissions that verified identity has.

Why It Matters

Confusing these two concepts leads to serious security holes. For example, a team might build a strong multi-factor login system, but forget to check permissions on their API endpoints. In that scenario, an attacker can create an ordinary, verified account (passing authentication), and then view other people's private data or access administrative features simply by requesting the API directly, because the server never checked authorization.

How It Works

In a secure application, requests pass through a clear two-step sequence: 1. The Authentication Step (Who are you?): • The user submits credentials (such as username, password, or MFA code) over HTTPS. • The authentication server verifies the credentials. • If successful, the server issues an encrypted session cookie or a signed token (JWT) identifying the user. • If the user fails to provide valid credentials, the server responds with HTTP 401 Unauthorized (which really means 'unauthenticated: please log in'). 2. The Authorization Step (What can you do?): • The authenticated user attempts an action (such as deleting a user account). • The server checks the user's identity from the session or token. • The server checks its permission rules: Does this user have permission to delete accounts? • If yes, the request completes (HTTP 200). • If no, the server rejects the request with HTTP 403 Forbidden (which means 'we know who you are, but you do not have permission for this action'). 3. Understanding HTTP 401 vs HTTP 403: • HTTP 401 Unauthorized: The request lacks valid authentication credentials. The system does not know who you are. • HTTP 403 Forbidden: The system knows who you are, but you do not have permission to access the requested resource.

The Request Pipeline: How Authentication Precedes Authorization

1. Incoming API Request
A client submits a request with an authentication token or session cookie
2. Authentication Middleware
The server validates the token signature and expiration; if invalid, it returns HTTP 401
3. Identity Attached to Context
The server attaches verified user details (ID, roles, organization) to the request object
4. Authorization Middleware
The server verifies whether the user's role has permission to access the requested endpoint; if not, it returns HTTP 403
5. Controller Execution
The application runs its business logic and database queries within safe boundaries
6. Response Returned
The server returns the requested data to the verified and authorized client

Key Points

  • AuthN establishes identity (Who you are); AuthZ enforces permissions (What you can do).
  • Authentication must always happen before Authorization can take place.
  • HTTP 401 means missing or invalid authentication; HTTP 403 means insufficient permissions.
  • A user can be fully authenticated and still be completely unauthorized for a specific page or action.
  • UI permission checks help guide users, but backend authorization checks enforce actual security.

Steps

  1. Authenticate at the Network Ingress

    Verify session cookies, tokens, or digital certificates at your API gateway before forwarding requests deeper into internal services.

  2. Pass Verified Identity Context

    Forward verified identity information to internal microservices using cryptographically signed headers or tokens.

  3. Authorize at Every Service Layer

    Do not assume internal network calls are pre-authorized; verify permissions at every endpoint and database query independently.

  4. Use Proper HTTP Status Codes

    Return HTTP 401 when authentication is missing or invalid; return HTTP 403 when a recognized user lacks permission for that action.

Examples

The Airline Boarding Analogy

• Authentication: At the airport security line, you show your government passport. The officer verifies that the photo matches your face and confirms who you are. You are now allowed inside the terminal. • Authorization: You walk to the gate for Flight 200 to New York and scan your boarding pass. If your ticket was for Flight 150 to Chicago, the scanner buzzes red and stops you. The airline knows who you are (Authentication), but you do not have permission to board that specific plane (Authorization).

Real-World Examples

The Equifax Portal Configuration Flaw (2017)

An internal dispute portal required a username and password, meaning authentication was in place. However, the system used default credentials and once logged in, had no authorization checks or data segregation. An account could query sensitive credit records for over 140 million consumers without any restriction.

Technical Examples

Separating AuthN and AuthZ Middleware in Express.js / TypeScripttypescript
import { Request, Response, NextFunction } from "express";
import jwt from "jsonwebtoken";

interface AuthRequest extends Request {
  user?: {
    id: string;
    role: "student" | "instructor" | "admin";
  };
}

// ─── 1. AUTHENTICATION (AuthN): Verifies WHO you are ────────────────────────
export function requireAuth(req: AuthRequest, res: Response, next: NextFunction) {
  const token = req.cookies?.session_token || req.headers["authorization"]?.split(" ")[1];

  if (!token) {
    // 401 Unauthorized: Client failed to authenticate
    return res.status(401).json({
      error: "Authentication Required",
      message: "Please log in to obtain access credentials.",
    });
  }

  try {
    const payload = jwt.verify(token, process.env.JWT_PUBLIC_KEY!, { algorithms: ["RS256"] }) as any;
    req.user = { id: payload.sub, role: payload.role };
    next(); // Identity verified; proceed to next step
  } catch (err) {
    // 401 Unauthorized: Token is expired, invalid, or forged
    return res.status(401).json({ error: "Invalid or expired session token." });
  }
}

// ─── 2. AUTHORIZATION (AuthZ): Verifies WHAT you can do ─────────────────────
export function requireRole(allowedRoles: Array<"student" | "instructor" | "admin">) {
  return (req: AuthRequest, res: Response, next: NextFunction) => {
    // Confirm authentication has already succeeded
    if (!req.user) {
      return res.status(500).json({ error: "Server error: Authorization ran before Authentication." });
    }

    if (!allowedRoles.includes(req.user.role)) {
      // 403 Forbidden: Identity is known, but lacks required permissions
      return res.status(403).json({
        error: "Forbidden",
        message: `User role '${req.user.role}' is not authorized for this operation.`,
      });
    }

    next(); // Authorization verified; proceed to controller
  };
}

// ─── PIPELINE ATTACHMENT ───────────────────────────────────────────────────
// To delete a course, the request must pass requireAuth FIRST, then requireRole('admin')
// app.delete('/api/courses/:id', requireAuth, requireRole(['admin']), deleteCourseController);
This demonstrates clean separation in middleware. `requireAuth` confirms identity and returns HTTP 401 if unauthenticated. Once `req.user` is set, `requireRole` checks permissions and returns HTTP 403 if the user does not hold an authorized role.

Authentication (AuthN) vs Authorization (AuthZ)

AspectAuthentication (AuthN)Authorization (AuthZ)
Core Question'Who are you?' (Identity verification)'What are you allowed to do?' (Permission enforcement)
When It HappensEvaluated first at login or at the API gatewayEvaluated on every single action and record access
HTTP Status CodeHTTP 401 Unauthorized (unauthenticated)HTTP 403 Forbidden (unauthorized)
Data UsedPasswords, security keys, authenticator codes, biometric scansUser roles, permissions lists, resource ownership, policy rules
Common Failure CauseWrong password, expired session token, or invalid signatureStandard user trying to view admin tools or another user's data
User Action NeededRedirect the user to log inShow an access denied notice explaining missing permissions

Advantages

  • Independent Modules: Identity management can be updated or swapped without rewriting business permission rules.
  • Better Monitoring: Security teams can easily tell the difference between credential brute-force attacks (spikes in 401s) and permission tampering (spikes in 403s).
  • Standards-Based: Follows standard industry practices outlined in OAuth 2.0 and NIST guidelines.

Limitations

  • Implementation Discipline: Developers must consistently apply both checks across all backend routes and API endpoints.

Interview Questions

Can an API return an HTTP 403 Forbidden response if a request is completely unauthenticated?

Technically yes, an API gateway can respond with 403 Forbidden if a client's IP address is blocked before login is attempted. However, by standard REST conventions, unauthenticated requests that need a login should receive 401 Unauthorized, while authenticated requests that lack sufficient permissions should receive 403 Forbidden.

Practice Questions

  1. In your application, trigger both conditions: submit an expired token to confirm you get a 401, then log in with a basic account and try opening an admin route to confirm you receive a 403.