Course contents

12. Security and Identity Lesson 1 of 8

Authentication vs Authorization

Who is calling versus what they may do: 401 vs 403, coarse checks at the gateway, object-level checks in the service, and the cost of a policy engine.

14 minIntermediate9 steps
Loading the interactive simulation…
Loading the knowledge check…

Summary

  • Authentication establishes identity once per login; authorization decides every request against a specific resource.
  • 401 means the caller is not authenticated; 403 means they are, and the answer is no. 404 can hide that a resource exists.
  • Gateways enforce coarse rules (valid token, scope, rate limit); only the service that owns the data can check ownership.
  • Broken object-level authorization (BOLA) is the most common API vulnerability: check every object id against the caller.
  • Authorization fails closed, so a remote policy engine sits on every request’s critical path; local evaluation of distributed policies avoids that.
Deep diveHow it works, trade-offs, failure modes, misconceptions and the interview angle.

What it is

Authentication (authn) establishes who is calling: a person, a device or another service. It ends with a credential the system can check on later requests, such as a session cookie or a signed token.

Authorization (authz) decides whether that caller may perform a specific action on a specific resource: may Alice read invoice 42, may the billing service publish to this topic. It needs the identity from authentication, plus rules and often data about the resource.

Why it exists

Knowing who someone is does not tell you what they may do. Every signed-in user is authenticated; almost none of them may read everyone else’s data. Keeping the two apart lets each be solved well: identity once, in a dedicated system (an identity provider), and permissions on every request, close to the data they protect.

How it works

Authentication happens at login. The user proves identity with something they have or are (a passkey, a hardware key) and often something they know (a password). The identity provider issues a credential: a session id stored server-side, or a signed token listing claims such as the subject (sub), issuer and expiry. Later requests carry the credential, and servers verify it without asking the user again.

Authorization happens on every request. Common models:

  • RBAC (role-based): users get roles, roles get permissions. Simple; coarse, and roles multiply.
  • ABAC (attribute-based): rules over attributes of the user, the resource and the context (department, record owner, time, IP range).
  • ReBAC (relationship-based): permissions follow relationships, as in Google’s Zanzibar paper (“Alice is an editor of folder F, which contains document D”).

Where checks run. A policy enforcement point (the gateway, the service, a sidecar) intercepts the request and asks a policy decision point for allow or deny. The decision point can be code inline in the service, a library evaluating policy files (OPA/Rego, Cedar), or a remote service. Gateways are good at coarse checks that need only the request and the token: is the token valid, does it carry the scope for this route, is the caller within its rate limit. Only the service that loads the object can check ownership, tenancy or record state.

Status codes. RFC 9110 defines 401 Unauthorized as “lacks valid authentication credentials”; the response carries a WWW-Authenticate header that tells the client how to authenticate. 403 Forbidden means the server understood who is asking and refuses. A server may answer 404 instead of 403 to avoid confirming that a resource exists.

When to use it

Always: every endpoint that is not deliberately public needs both. The design decisions are where each check runs, which model fits your rules, and whether to centralize policy. Centralize when many services share rules that change often and must be audited (compliance, multi-tenant SaaS). Keep simple, local checks when rules are few and owned by one service.

When not to

  • Don’t put authorization only in the UI (hiding buttons). Anything the server does not check, a client can call directly.
  • Don’t rely only on the gateway for anything that depends on the object being accessed.
  • Don’t add a remote policy engine call per request if your rules fit in a few lines of code and change rarely; the network hop and the extra dependency cost more than they give.

Trade-offs

Choice You gain You pay
Checks at the gateway Junk rejected early, one place for token validation and rate limits Cannot see objects; services that trust it blindly are exposed if anything bypasses it
Checks in each service Object-level decisions with the data at hand Rules scattered across codebases, uneven quality
Remote policy engine (per request) One place for rules, testing and audit logs A network round trip per decision; its outage denies every request (fail closed)
Local evaluation of distributed policies Fast decisions that survive the policy server being down Rules arrive with a delay; data the rule needs must be available locally
404 instead of 403 Does not reveal which ids exist Harder debugging for legitimate users

Alternatives

  • Inline checks in code: if (invoice.ownerId != caller.id) return Forbid(). Fine for small systems; hard to audit at scale.
  • Database-enforced rules: row-level security in the database filters rows by the caller. Strong defence in depth; ties authorization to one store.
  • Capability tokens: the token itself names exactly what it allows (a pre-signed URL for one object). No lookup; revocation is hard, so keep them short-lived.

Failure modes

  • Broken object-level authorization (BOLA/IDOR): endpoints accept an object id and never check it against the caller. First on the OWASP API Security Top 10 (2023).
  • Broken function-level authorization: admin endpoints reachable by ordinary users because only the UI hid them.
  • Fail open: a policy call times out and the code treats “no answer” as “allow”.
  • Policy engine as a single point of failure: per-request remote decisions make its availability an upper bound on yours.
  • Confused deputy: service A, with broad permissions, acts for a user on service B without passing the user’s identity, so B authorizes A instead of the user.
  • Stale permissions: roles cached in long-lived tokens keep working after they are removed (see the JWT lesson).

In production

Deny by default and grant the least privilege needed. Pass the end user’s identity through service calls (a token or a signed context), not only the calling service’s identity. Write authorization tests for every endpoint: “user B cannot read user A’s resource” is a test case, not a code review hope. Log decisions with the policy version and the reason. If you centralize policy, prefer a library or sidecar evaluating pushed bundles over a remote call per request, and monitor how old each service’s bundle is.

Common misconceptions

  • “401 means not allowed.” Despite its name, 401 means not authenticated. Not allowed is 403.
  • “A valid token means the request is allowed.” It means you know who is asking. What they may do with this object is a separate decision.
  • “The gateway handles security, so services can skip it.” Gateways do not see objects, and internal calls may not pass through the gateway at all.
  • “OAuth scopes are permissions on data.” Scopes limit what a client application may do on the user’s behalf; they do not say which records the user may touch.

Interview angle

Expect to separate the two terms crisply, pick 401 vs 403, and then place checks in a design: token validation and rate limits at the gateway, ownership and tenancy in the service, defence in depth with database row-level security for multi-tenant data. Strong answers mention BOLA by name, explain fail-closed behaviour and how to keep a policy engine off the critical path (local evaluation, bundles), and propagate user identity across service calls.

Model assumptions

Steps 1–5 are a scripted illustration, not a simulation: logins, credentials and decisions are drawn as hand-placed packets with illustrative durations (12 ms to the gateway, 4 ms between internal components, 14 ms to the identity provider). The engine has no notion of identities or permissions. Steps 6–9 use the simulation: Poisson arrivals at 300 requests per second, a gateway with 1 ms of work, an invoice service with 32 workers and 3 ms mean service time (lognormal, cv 0.3), a database with 16 connections and 3 ms reads, and a policy engine with 8 workers, 2 ms per decision and 2 ms network distance. A failed policy engine refuses connections, and the service then fails the request (fail closed). Local policy evaluation is modelled as 0.5 ms of extra service time. Numbers are illustrative, not benchmarks of any product.

The lesson as textEvery step of the simulation, written out.
  1. 1. Authentication: proving who is calling

    Alice signs in at the identity provider with a passkey (or a password plus a second factor). The identity provider checks the proof and hands back something the rest of the system can check cheaply on every request: a session cookie or a signed token that says sub=alice.

    That is authentication (authn): establishing *who* the caller is. It says nothing yet about what Alice may do. This step is a scripted illustration: the packets are placed by hand.

    Scene: Alice sends her login proof to the identity provider, which answers with a credential (a token) naming her as the subject.

    Key idea: Authentication answers "who is this?" and produces a credential the system can verify on later requests.

  2. 2. Authorization: deciding what the caller may do

    Alice asks for GET /invoices/42 with her credential attached. The gateway checks the credential, the invoice service loads invoice 42 and checks a rule: invoices may be read by their owner (or by someone in the owner’s finance team). Invoice 42 belongs to Alice, so the answer is yes.

    That is authorization (authz): given a known caller, deciding whether *this action on this resource* is allowed. Authentication happens once per login; authorization happens on every request, for every resource touched.

    Scene: Alice’s request passes the gateway, which identifies her; the invoice service loads invoice 42 from the database, sees that Alice owns it and returns it.

    Key idea: Authorization answers "may this caller do this action on this resource?" and runs on every request.

  3. 3. 401 means "who are you?", 403 means "no"

    First, a request arrives with no valid credential (missing, expired or with a bad signature). The gateway answers 401 Unauthorized with a WWW-Authenticate header: despite its name, 401 means *unauthenticated*, and the client should sign in or refresh its token.

    Then Bob, who is signed in, calls DELETE /invoices without the right permission. The gateway answers 403 Forbidden: it knows who Bob is, and the answer is no. Signing in again will not help. When even admitting that a resource exists would leak information, services answer 404 instead of 403.

    Scene: A request with an expired token is rejected by the gateway with 401. Then Bob, signed in but without the delete permission, is rejected by the gateway with 403.

    Key idea: 401 = not authenticated (retry with credentials). 403 = authenticated but not allowed (do not retry).

  4. 4. The gateway cannot see who owns invoice 42

    The team moved all checks into the gateway: is the token valid, does it carry the invoices:read scope, is the caller within the rate limit. The invoice service trusts that anything reaching it is allowed.

    Bob has a valid token with invoices:read, and asks for GET /invoices/42, Alice’s invoice. The gateway lets it through: nothing in the URL or the token says who owns invoice 42. The service returns it. This is broken object-level authorization (BOLA), first on the OWASP API Security Top 10 (2023).

    Scene: Bob requests Alice’s invoice. The gateway accepts his valid token and scope, the service loads the invoice and, without checking the owner, returns it to Bob.

    Key idea: A gateway can check who you are and coarse permissions, but not whether you own a specific object.

  5. 5. The service checks the object

    The fix is to check authorization where the data is. The service loads invoice 42, sees owner = alice, compares it with the caller bob, and answers 403 (or 404, so Bob cannot even probe which invoice numbers exist).

    A common split: the gateway does authentication and coarse checks that need no business data (valid token, scope, tenant header, rate limit), and rejects junk early. The service does fine-grained checks that need the object (owner, team, record state). Services still verify the token themselves, or at least accept requests only from the gateway over an authenticated channel.

    Scene: Bob requests Alice’s invoice again. The service loads it, sees that Alice owns it and returns 403, which the gateway passes back to Bob.

    Key idea: Coarse checks at the edge, object-level checks in the service that owns the data. Never only at the edge.

  6. 6. Centralize the rules in a policy engine

    Ownership rules multiply: owners, finance teams, auditors, support staff with a ticket. Many teams move them into a policy engine (a *policy decision point*, PDP, such as OPA or Cedar-based services). The service loads the invoice, then asks the PDP: *may alice read invoice 42 with owner alice?*

    The simulation now runs 300 requests per second. Every request makes one more network round trip plus the decision: about 6 ms more per request here (32 → 38 ms). Rules now live in one place, can be reviewed and tested, and every decision can be logged.

    Scene: Users send 300 requests per second through the gateway to the invoice service, which reads the invoice from the database and then asks the policy engine for a decision. Latency is about 38 ms.

    Key idea: A remote policy engine centralizes rules and audit, at the cost of a network call on every request.

  7. 7. The policy engine fails: deny everything

    One second in, the policy engine goes down. The service cannot get a decision, so it does the safe thing and fails closed: no decision, no access. Every request now fails.

    Failing closed is right for security (failing *open* would hand out data to anyone while the PDP is down), but it turns the PDP into a dependency of every single request. Its availability caps the availability of everything behind it.

    Scene: The policy engine goes offline after one second. The invoice service cannot get decisions and every request fails.

    Key idea: Authorization must fail closed, so a remote decision point is on the critical path of every request.

  8. 8. Evaluate policy locally, distribute the rules

    Instead of calling the PDP per request, the service runs the policy engine in process (a library or a sidecar on the same host) and the central server only distributes policy bundles. The service received the current bundle when this step starts (the async message), and decides locally in about half a millisecond.

    The policy server fails again after 1.5 s, and nothing happens: the service keeps deciding with the last bundle it has. Latency is back near 32 ms. The price: rules reach services with a delay, and decisions that need fresh data (group memberships, ownership) still need that data on hand.

    Scene: The policy server pushes a policy bundle to the invoice service, which now decides locally. When the policy server fails again after 1.5 seconds, requests keep succeeding at about 32 ms.

    Key idea: Central rules, local decisions: distribute policy, keep the decision off the network path.

  9. 9. Two questions, every request

    Authentication establishes who is calling, once per login, and yields a credential that is cheap to verify. Authorization decides, on every request, whether this caller may do this action to this object.

    Answer 401 when you do not know the caller and 403 (or 404) when you do and the answer is no. Reject cheap things at the gateway, check objects in the service that owns them, and if you centralize rules, keep the decision itself close to the code so it is fast and survives the policy server being down.

    Scene: Users send 300 requests per second through the gateway to the invoice service, which reads invoices and decides access locally from the policy bundle. Nothing fails.

    Key idea: Authn once, authz always; deny by default; check objects where the data lives.