Skip to content
Tutorials Center
My learning

Topics

Lesson 16 of 39 ยท Authentication Basics

Authentication vs Authorization

Understand authentication (who are you) versus authorization (what may you do) in APIs: 401 versus 403, credential types, roles and ownership checks, with working examples.

Two words that sound alike, and two completely different questions an API must answer on every protected request:

  • Authentication (often shortened to authn): who are you? The server verifies a claimed identity using credentials such as a password, an API key or a token.
  • Authorization (authz): what are you allowed to do? Given a known identity, the server decides whether this specific action on this specific resource is permitted.

Mixing them up is the root of many security bugs. An API that authenticates correctly but forgets authorization lets any logged-in user read anyone's data. That mistake is common enough that it tops the OWASP API Security list (Broken Object Level Authorization).

Two questions, two status codes

flowchart TD
    A["Request to a protected endpoint"] --> B{"Valid credentials?"}
    B -- "No or missing" --> C["401 Unauthorized + WWW-Authenticate"]
    B -- Yes --> D{"Allowed to do this?"}
    D -- No --> E["403 Forbidden (or 404 to hide existence)"]
    D -- Yes --> F["Run the handler"]

Authentication happens first; authorization second.

Situation Status Meaning
No token, expired token, wrong password 401 "I do not know who you are". Include a WWW-Authenticate header naming the scheme
Valid user, but not an admin 403 "I know who you are, and you may not do this"
Valid user asks for another user's private order 404 or 403 Use 404 if you do not want to confirm the order exists

The name of 401 Unauthorized is a historical accident: it really means unauthenticated. Retrying with correct credentials can fix a 401; no amount of re-logging-in fixes a 403.

Credentials: what proves identity

Type How it works Typical use
Password User types a secret; server compares a hash Human login (see password hashing)
API key Long random string sent in a header Server-to-server, developer APIs (basic auth and API keys)
Session cookie Opaque id referring to server-side state Browser apps (sessions and cookies)
Bearer token (JWT, opaque) Signed or random token in Authorization SPAs, mobile apps, microservices
OAuth 2.0 / OpenID Connect Delegated login via a provider "Sign in with Google", third-party access
Mutual TLS Client certificate Service meshes, high-security B2B

Multi-factor authentication (MFA) adds a second proof (a one-time code, a hardware key). Passkeys (WebAuthn) replace passwords with public-key cryptography. This chapter starts with the basics; later chapters cover tokens and OAuth.

Authorization models

Once you know the user, how do you decide?

  1. Role-based access control (RBAC). Users have roles (admin, editor, viewer); roles carry permissions. Simple and widely used.
  2. Ownership checks. "A user may edit their own orders." This needs the resource, not just the role.
  3. Attribute-based access control (ABAC). Rules over attributes: department, time of day, document status.
  4. Scopes. A token carries scopes such as orders:read, limiting what an application may do on the user's behalf (central to OAuth).

Real systems combine them: a role grants the capability ("editors can edit articles") and an ownership or state check narrows it ("only their own draft articles").

Where to check

Authorize on the server, on every request, as close to the data as possible. Never trust the client: hiding a "Delete" button in the UI is a convenience, not security, because anyone can send the DELETE request by hand. Check both function-level access (may this role call DELETE /orders/:id at all?) and object-level access (is this order theirs?).

Authentication or authorization?

Who are you? Authentication. Fails with 401.
May you do this? Authorization. Fails with 403.
Every request Both checks run on the server each time.
1 / 2

An API with both checks

The server below has a small token table for authentication, and two kinds of authorization: a role check on GET /users (admins only) and an ownership check on GET /orders/:id. Notice that the order endpoint answers 404 when you ask for someone else's order.

Node.js 401, 403 and ownership checks

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Permissions as data

Hard-coding if (user.role === 'admin') in every handler scatters your policy. A small permission table keeps rules in one reviewable place and makes tests easy:

Node.js A tiny role and ownership policy

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Notice the default is deny: an unknown role or an action not in the table is refused. Secure systems are built on "deny unless explicitly allowed".

Threats to keep in mind

  • Credential stuffing and brute force: attackers try leaked passwords. Rate-limit login and use MFA (see the security chapter).
  • Insecure Direct Object References (IDOR/BOLA): changing an id in the URL to reach someone else's data. Fix with object-level checks.
  • Privilege escalation: a normal user changing their own role via mass assignment (validation).
  • Token leakage: tokens in URLs end up in logs and browser history; send them in headers.
  • Leaky errors: different messages for "no such user" and "wrong password" reveal valid accounts.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A request arrives without any credentials. Which status should the API return?

    401 means the caller is not authenticated. 403 is for authenticated callers who lack permission.
  2. 2. Bob is logged in and requests GET /orders/2, which belongs to Eve. Which design is best?

    Authentication is not authorization. An object-level check must verify Bob may see that order.
  3. 3. Why is hiding the Delete button in the UI not a security measure?

    Client-side checks are only a convenience. Enforce access on the server.
  4. 4. What is the safest default in an authorization policy?

    Default deny means a missing rule fails closed instead of exposing data.

Summary

  • Authentication proves identity; authorization decides what that identity may do. Both run on every request, on the server.
  • Use 401 (plus WWW-Authenticate) for missing or invalid credentials, 403 for lack of permission, and sometimes 404 to hide existence.
  • Credentials include passwords, API keys, session cookies, bearer tokens, OAuth and client certificates.
  • Combine roles (function-level) with ownership checks (object-level); default to deny.
  • Never trust ids or roles sent in the body or hidden in the UI.

Next: Password Hashing