DevAtlas

Learn

  • Dashboard
  • Learning Paths
  • All Categories
  • Topics

Practice

  • Interview Questions
  • Flashcards
  • Quizzes
  • Study Plans

Personal

  • Bookmarks
  • Notes
  • Progress
  • PDF Library
  • Settings
  • About
  1. Topics
  2. Authentication vs Authorization
0%
Authentication and Authorization

Authentication vs Authorization

Authentication proves who you are; authorization decides what you may do. Learn the difference and how it maps to HTTP 401 vs 403.

Beginner20 min study9 min read
Export PDF

Learning objectives

  • Define authentication (authN) and authorization (authZ) and state precisely how they differ.
  • Explain why authentication always happens before authorization in a request pipeline.
  • Map the two concepts to HTTP: 401 Unauthorized (unauthenticated) vs 403 Forbidden (not permitted).
  • Recognise common authorization models such as roles (RBAC), attributes (ABAC), and scopes.

Simple explanation

Picture a hotel. At the front desk you show your passport to prove you really are the person on the booking — that is authentication. In return you get a key card. That card only opens *your* room and the gym, not the manager's office or other guests' rooms — that is authorization. Two different questions: *"Who are you?"* and then *"What are you allowed to do?"*

  • Authentication (authN) = proving who you are.
  • Authorization (authZ) = deciding what you may do.

You can't be authorized before you're authenticated. The hotel can't decide which doors your card opens until it knows who you are.

Technical explanation

Authentication verifies identity. The user (or service) presents credentials — a password, a one-time MFA code, a client certificate, a signed token — and the system confirms they match a known identity. The output of authentication is a trusted answer to *"who is making this request?"*, usually represented as a session or a token (e.g. a JWT) attached to every subsequent request.

Authorization happens *after* identity is established. Given a known identity, the system decides whether that identity is permitted to perform a specific action on a specific resource. Common models:

  • RBAC (Role-Based Access Control) — permissions are attached to roles (admin, editor, viewer), and users are assigned roles.
  • ABAC (Attribute-Based Access Control) — decisions use attributes of the user, resource, and context (e.g. "owner can edit", "only during business hours").
  • Scopes — OAuth access tokens carry scopes like read:orders or write:orders that limit what the token may do.

The order is fixed: authN first, authZ second. A valid identity with no permission is still denied.

Why it matters

Confusing the two leads to real security bugs. If you only authenticate and never authorize, any logged-in user can reach admin endpoints. If you authorize on the client only (hiding a button) but skip the server check, an attacker simply calls the API directly. Getting this distinction right is the backbone of access control in every serious application.

How it works

A typical request pipeline:

  1. The client sends a request with a credential — a session cookie or an Authorization: Bearer <token> header.
  2. Authentication middleware validates the credential (checks the session store, or verifies the token's signature and expiry). If it fails or is missing → 401 Unauthorized.
  3. The request now has a known identity (req.user).
  4. Authorization middleware checks whether that identity has the required role/permission/scope for this route. If it fails → 403 Forbidden.
  5. Only if both pass does the handler run the business logic.

Real-world analogy

Think of an airport. Authentication is the passport check — the officer confirms you are who your passport says. Authorization is your boarding pass — it decides *which* flight and *which* seat you may board. A valid passport (you're authenticated) does not let you board a flight you didn't buy a ticket for (you're not authorized). And you can't get a boarding pass to work without first proving your identity.

Important terminology

  • Credentials — the proof of identity a user presents (password, MFA code, token, certificate).
  • MFA (Multi-Factor Authentication) — combining two or more factors (something you know, have, or are) to strengthen authentication.
  • Permission / scope — a specific right to perform an action, e.g. delete:invoice or the OAuth scope read:profile.
  • Principle of least privilege — grant each identity only the permissions it truly needs, and nothing more.

Key definitions

Authentication (authN)
The process of verifying who a user or service is, by validating credentials such as a password, MFA code, or token.
Authorization (authZ)
The process of deciding what an already-identified user is permitted to do, using roles, permissions, or scopes.
RBAC
Role-Based Access Control: permissions are attached to roles, and users gain permissions by being assigned those roles.
Scope
A granular permission carried by an access token (e.g. read:orders) that limits which actions the token may perform.

Must memorize

Must memorize

  • Authentication = who you are; authorization = what you may do.
  • AuthN always comes before authZ — you can only authorize a known identity.
  • 401 Unauthorized = not (properly) authenticated; 403 Forbidden = authenticated but not permitted.
  • Always enforce authorization on the server; the client UI is never a security boundary.

Real-world example

Deleting a blog post

A logged-in reader sends DELETE /posts/12 with a valid session — they are authenticated, so the server does not return 401. But deletion requires the "editor" role, and a reader does not have it, so authorization fails and the server returns 403 Forbidden. Same identity, different outcome depending on permission.

An expired token hitting an API

A mobile app calls GET /me with a JWT whose expiry has passed. Authentication middleware verifies the signature but sees exp is in the past, so identity cannot be trusted and the API returns 401 Unauthorized. The app then uses its refresh token to obtain a fresh access token and retries.

Code example

auth-middleware.ts
import type { Request, Response, NextFunction } from 'express';
import jwt from 'jsonwebtoken';

// 1) Authentication: prove WHO the caller is.
function authenticate(req: Request, res: Response, next: NextFunction) {
  const header = req.headers.authorization; // "Bearer <token>"
  const token = header?.startsWith('Bearer ') ? header.slice(7) : null;

  if (!token) {
    // No credential at all -> not authenticated.
    return res.status(401).json({ error: 'Authentication required' });
  }

  try {
    const payload = jwt.verify(token, process.env.JWT_SECRET!) as {
      sub: string;
      role: string;
    };
    req.user = { id: payload.sub, role: payload.role };
    next();
  } catch {
    // Invalid or expired token -> still unauthenticated.
    return res.status(401).json({ error: 'Invalid or expired token' });
  }
}

// 2) Authorization: decide WHAT the (known) caller may do.
function requireRole(role: string) {
  return (req: Request, res: Response, next: NextFunction) => {
    if (!req.user) {
      return res.status(401).json({ error: 'Authentication required' });
    }
    if (req.user.role !== role) {
      // Authenticated, but lacks the permission.
      return res.status(403).json({ error: 'Insufficient permissions' });
    }
    next();
  };
}

// Order matters: authenticate BEFORE authorize.
app.delete('/posts/:id', authenticate, requireRole('editor'), deletePost);

Express middleware: authenticate first (401 on failure), then authorize by role (403 on failure).

scope-check.ts
// Assumes authentication already ran and set req.user.
function canEditInvoice(req: Request, res: Response, next: NextFunction) {
  const user = req.user; // guaranteed by upstream authenticate()
  const invoice = res.locals.invoice;

  const isOwner = invoice.ownerId === user.id;
  const isAdmin = user.scopes.includes('write:invoices');

  if (isOwner || isAdmin) {
    return next(); // authorized
  }

  // Known identity, but not allowed to edit this specific resource.
  return res.status(403).json({ error: 'You cannot edit this invoice' });
}

Attribute/scope-based authorization: owners or admins pass, everyone else is forbidden.

Common mistakes

Mistake

Returning 403 when a request has no valid credentials (or 401 when the user is logged in but simply lacks permission).

Do this instead

Use 401 when authentication is missing or invalid, and 403 when the identity is known but not permitted for the action.

Mistake

Enforcing authorization only in the frontend — hiding a button or a route while leaving the API open.

Do this instead

Client-side checks are only UX. Every protected action must be authorized again on the server, which is the real trust boundary.

Interview questions

Quiz

Question 1 of 30 ✓
Which statement correctly distinguishes authentication from authorization?
Select an answer to continue.

Flashcards

Card 1 of 3

Show answer · Space

Summary

Authentication answers "who are you?" by verifying credentials; authorization answers "what may you do?" by checking roles, attributes, or scopes. Authentication always runs first. In HTTP, a missing or invalid identity yields 401 Unauthorized, while a valid identity without permission yields 403 Forbidden. Authorization must always be enforced on the server, never only in the UI.

References

  • MDN — HTTP 401 Unauthorized
  • OWASP — Authorization Cheat Sheet

Related topics

JWT (JSON Web Tokens)Access Tokens and Refresh TokensHTTP Status Codes
Next
JWT (JSON Web Tokens)

On this page

  • Learning objectives
  • Simple explanation
  • Technical explanation
  • Why it matters
  • How it works
  • Real-world analogy
  • Important terminology
  • Key definitions
  • Must memorize
  • Real-world example
  • Code example
  • Common mistakes
  • Interview questions
  • Quiz
  • Flashcards
  • Summary