Skip to content

Authentication and authorization

Phase 2 · The web and APIs · 14 min read

What you'll be able to do

  • Trace a request through identity, permission, and audit checks.
  • Choose a sensible credential for a user, browser, or service and explain its limits.
  • Catch an object-level authorization bug and verify a signed message without trusting its contents first.

Three checks in one request

Authentication establishes who is making a request. Authorization decides what that identity may do to this resource. Accounting or audit records what happened so an operator can investigate later. A successful login answers only the first question. If an API checks login and then returns any document whose ID appears in the URL, one customer can read another customer's document by changing that ID.

Every request: authenticate, authorize the action on this object, execute, audit.

Authorization uses the server-verified identity, action, and actual resource. Deny access when required facts are missing. Audit the actor, action, resource ID, and outcome, including denials; never log credentials.

Passwords prove knowledge, not permission

Never store plaintext or reversible passwords. Store a salted, slow password hash: a fresh random salt, algorithm, work settings, and derived hash. At login, derive again and compare. Equal passwords should yield different records because their salts differ. A salt is public; it blocks reuse of precomputed guesses across accounts.

Use a maintained library with Argon2, scrypt, or bcrypt and suitable work settings. SHA-256 alone is fast, so an attacker can try guesses rapidly after a database leak. A password hash makes each guess costly. Never invent your own scheme. The lab uses PBKDF2-HMAC to expose the mechanics, not to build a production login service.

Multi-factor authentication (MFA) adds another factor, such as an authenticator device. It limits damage from stolen passwords, but recovery paths and session theft still matter. MFA does not authorize access to another user's data.

Sessions, tokens, and browser storage

With a server-side session, a random cookie ID points to server state. Delete that state to revoke the session. Multiple app instances need shared session storage or routing to the instance holding it.

A signed token, such as a JWT, carries claims like subject, audience, and expiry. Verify its signature and required claims before trusting them. It needs no session lookup, but a stolen token stays valid until expiry unless you add revocation state or rotate the signing key. Reject unsigned tokens and unexpected algorithms. Short-lived access tokens go to APIs; longer-lived refresh tokens obtain new ones and need storage, rotation, and revocation controls.

In browsers, prefer an HttpOnly, Secure, SameSite cookie: JavaScript cannot read it, and Secure restricts it to HTTPS. SameSite limits when the browser attaches the cookie to cross-site requests; it does not block those requests, and some flows still need CSRF protection. Never put reusable tokens in URLs.

For example, {"sub":"u7","exp":2000} needs signature and expiry checks. Recheck authorization against current resource state even before expiry.

API keys and service identity

An API key identifies a developer or program calling an API. It supports scopes, quotas, and rotation, but a shared key cannot tell which human used it. A key can grant tenant access only when the server binds it to a principal and tenant and checks permission on the requested document. Use separate keys per caller with minimal scopes and a revocation plan.

Show a new key once. Store a prefix for lookup and a hash for verification, never the usable key. Keep keys out of URLs and git; URLs reach logs and browser history. Put service credentials in a secret manager or runtime environment, away from code, images, notebooks, and logs. Prefer distinct service accounts and short-lived credentials over shared long-lived secrets. Authorize each service request too.

Delegated access: OAuth and OIDC

Suppose a scheduling app needs your calendar without your password. OAuth 2.0 lets a user (resource owner) authorize a client through an authorization server to access a resource server. Scopes limit categories of access; they do not replace object checks.

In the authorization-code flow, the client redirects the browser to the authorization server. The authorization server authenticates the user if needed and obtains consent when required. It returns a short-lived code; the client exchanges it for tokens, then presents an access token to the resource server. With PKCE, the client sends a hashed one-time challenge first and proves it holds the matching verifier when exchanging the code, so an intercepted code alone is not enough; when state is used, the client checks it. OpenID Connect (OIDC) adds identity, including an ID token. OAuth access tokens are for delegated API access, not standalone login assertions.

Authorize the action and the object

Role-based access control (RBAC) grants permissions through roles. Ownership checks compare the verified user ID with a resource owner. Attribute-based access control (ABAC) evaluates tenant, classification, or membership. Combine these with least privilege and deny by default: reject unknown roles, actions, and missing ownership.

def can_edit(user, document):
    return user["id"] == document["owner_id"]

assert can_edit({"id": 7}, {"owner_id": 7})
assert not can_edit({"id": 8}, {"owner_id": 7})

Without that check, /documents/42 has an insecure direct object reference (IDOR), also called broken object-level authorization. Load document 42, then authorize it. Hiding Edit in the browser does not stop direct HTTP requests. Admin exceptions need server-verified roles. If 1,000 users each own 10 documents, a login-only check potentially exposes the other 9,990 to each caller.

Hash, sign, and encrypt for different jobs

Hashing makes a fixed-size digest; it neither hides data nor proves its sender. Password hashing adds salt and work. Signing detects changes. A MAC such as HMAC proves the sender knew a shared secret but cannot distinguish holders of that secret; a digital signature is verified with a public key and needs the matching private key to create. Encryption hides plaintext without the decryption key. Signed tokens remain readable unless separately encrypted.

For a webhook, HMAC the exact bytes and a timestamp, then use hmac.compare_digest against the supplied signature. Reject timestamps outside a short window to limit replay. Sign the timestamp too, or an attacker can replace it. == can reveal timing differences for secret-derived values.

For AI engineers

For AI engineers

A model endpoint needs an identity for each caller so you can enforce per-user quotas and rate limits. Keep LLM-provider keys out of notebooks and public repositories: a leaked key can be used by someone else. In multi-tenant RAG, filter candidate documents by the caller's permission at retrieval time, before chunks enter the prompt. For an agent with tools, prompt text is untrusted input. The model is not a permission boundary; each tool must check the verified caller and requested object itself. Later lessons cover those defenses in depth.

Common mistakes

  • Checking login but not ownership for a requested object (IDOR).
  • Inventing cryptography or accepting a JWT with alg: none or an unverified signature.
  • Issuing long-lived bearer tokens without a revocation plan.
  • Printing secrets or tokens in logs, notebooks, error messages, or URLs.
  • Comparing webhook signatures with == or trusting an unsigned timestamp.
  • Relying on a hidden client-side button as an authorization rule.

Check yourself

A user is logged in and changes /documents/7 to /documents/8. Document 8 belongs to someone else. Which check stops the leak?

After loading document 8, authorization must compare its owner or access policy with the server-verified user and requested action. Login alone is insufficient.

You need to disable one stolen browser credential immediately. Which is simpler to revoke: a server-side session or a self-contained signed token, and why?

A server-side session: disable its server record. A self-contained token may remain valid until expiry unless a revocation list or equivalent state is checked.

A webhook's HMAC covers only its body. The timestamp is checked for freshness but is not signed. What can an attacker change?

They can replay a captured body and valid signature with a new timestamp. Include the timestamp in the signed bytes, then reject timestamps outside the allowed window.

A RAG search returns a relevant chunk from another tenant. Why is a prompt telling the model to ignore it insufficient?

The unauthorized data has already reached the model. Retrieval must filter documents by the verified caller's permissions before any chunk enters the prompt.

Lab

In code/auth-basics/, implement five small boundaries: password hashing, signed tokens, webhook verification, object authorization, and API key storage. The signed token is a teaching format, not a JWT replacement. Read README.md, then fill in starter/lab.py without changing the tests. Run cd code/auth-basics && PYTHONPATH=starter python -m pytest tests -q. The tests demonstrate tampering, expiry, replay, and an IDOR attempt.

Go deeper