Distributed patterns and operations

Authentication and authorization: sessions, OAuth and JWT

Choose between server-side sessions and tokens, validate JWTs safely, explain the OAuth 2.0 authorization code flow with PKCE, and pick an authorization model.

Lesson15 min read
Video walkthrough: not recorded yet. The lesson below is complete without it.

The problem

A team builds a web app with a users table. After login the server keeps the session in memory and puts a random session id in a cookie. It works on one server. Then three things happen.

They add a second server behind a load balancer, and users are logged out at random, because a session created on server A is unknown to server B. They move sessions to Redis, and every request now pays for a Redis lookup.

They split the app into 20 services. Each one needs to know who the caller is. Should every service call the session store, or trust a header set by whoever called it?

A partner wants to build an app that reads users’ data. The only way is for users to type their password into the partner’s app, which gives the partner full access, permanently, with no way to withdraw it short of changing the password. Asking for a user’s password to another site was common on the web in the 2000s, and OAuth was created to end it.

These are separate problems: storing credentials, remembering a login, delegating access to a third party, and deciding what each caller may do.

Authentication and authorization

Authentication (authN) establishes who the caller is. Authorization (authZ) decides whether that caller may perform this action on this resource. A failed authentication is HTTP 401. A failed authorization is 403.

Keep them apart in a design. Authentication usually happens once at the edge, in an API gateway. Authorization belongs close to the data, in the service that owns the resource.

Storing passwords

Never store a password in plaintext or encrypted reversibly, and never with a fast hash such as MD5 or SHA-256, which attackers can compute billions of times a second on GPUs. Use a deliberately slow, salted password hash: Argon2id is the first choice in OWASP’s guidance, with bcrypt and scrypt as established alternatives. A unique random salt per user defeats precomputed tables and makes identical passwords hash differently. Add rate limiting on login and offer a second factor.

The safest password store is the one you do not run. Delegating login to an identity provider, or using passkeys, removes the problem.

Sessions and tokens

Server-side session Self-contained token (JWT)
Client holds An opaque random id Signed claims
Server checks by Looking up the id in a store Verifying a signature locally
Revocation Delete the record, immediate Not possible before expiry without extra state
Cost A lookup and a shared store Larger requests, stale claims

A session cookie should be HttpOnly, Secure and SameSite. A JSON Web Token lets any service holding the issuer’s public key verify the caller with no network call, which suits a system of many services.

JWT structure and validation

A JWT is three base64url parts joined by dots: header.payload.signature. The header names the algorithm (alg) and key id (kid). The payload holds claims such as iss (issuer), sub (subject), aud (audience) and exp (expiry). The signature covers the first two parts. A JWT is signed, not encrypted, so anyone can read the payload. Do not put secrets in it.

Prefer asymmetric signatures (RS256, ES256) across services. With HS256, every verifier holds the shared secret and could also mint tokens.

To validate:

  1. Accept only the algorithms you configured.
  2. Verify the signature with the issuer’s key for that kid.
  3. Check iss is the issuer you expect and aud includes your service.
  4. Check exp, allowing a few seconds of clock skew.
  5. Only then read scopes or roles.

JWT pitfalls

  • Alg confusion. The header is attacker-controlled. Libraries that trusted it accepted tokens with alg: none, or tokens “signed” with HS256 using the server’s public RSA key as the secret. Both were found in several libraries in 2015. Pin the algorithm on the server.
  • Revocation. A token is valid until exp. Keep access tokens short, 5 to 15 minutes is typical, and revoke through refresh tokens. For instant revocation, keep a small denylist of token ids or a per-user “not valid before” time in a cache, accepting that this puts a lookup back.
  • Long lifetimes. A 30-day JWT is a 30-day password that cannot be changed.
  • Missing audience check. A token issued for one service is replayed against another.
  • Browser storage. A token in localStorage can be read by any injected script. An HttpOnly cookie cannot, but then you need CSRF defences.

OAuth 2.0 and the authorization code flow

OAuth 2.0 (RFC 6749, 2012) is a framework for delegated authorization: a user grants an app limited access to their data without sharing a password. It has four roles: the resource owner (the user), the client (the app), the authorization server (which authenticates the user and issues tokens) and the resource server (the API).

OAuth 2.0 authorization code flow with PKCE4 components: Client app, System browser, Authorization server, Resource server. Connections: Client app and System browser (front channel); System browser and Authorization server; Client app and Authorization server (back channel); Client app to Resource server (access token).Client appmobile app, public clientwants accessSystem browserthe user signs in hereAuthorizationserverlogin, consent, tokensResource serverthe APIfront channelback channelaccess token

Step 1 of 9

A user wants a mobile app to read their data from an API. The app must never see the user's password. Only the authorization server handles credentials, and it will hand the app a token limited to what the user approves.

Read the steps as text
  1. A user wants a mobile app to read their data from an API. The app must never see the user's password. Only the authorization server handles credentials, and it will hand the app a token limited to what the user approves.
  2. The app creates a long random string called the code verifier and keeps it in memory. It hashes the verifier with SHA-256 to get the code challenge. It also creates a random state value to recognise its own request later.
  3. The app opens the system browser at the authorization endpoint. The request carries the client id, the redirect URI, the scopes it wants, the state and the code challenge. The verifier itself is not sent.
  4. The user signs in on the authorization server's own page and approves the requested scopes. The app is not involved in this step, so it never handles the password or the second factor.
  5. The authorization server redirects the browser back to the app's redirect URI with a short-lived, single-use authorization code and the state. This is the front channel, where a malicious app or a log could see the code.
  6. The app checks that the state matches, then calls the token endpoint directly over TLS. It sends the authorization code together with the original code verifier.
  7. The authorization server hashes the verifier and compares it with the challenge it stored. They match, so it returns an access token and a refresh token. A thief who intercepted the code has no verifier, so the code is useless to them.
  8. The app calls the API with the access token in the Authorization header. The API checks the token's signature, issuer, audience, expiry and scopes before it returns any data.
  9. The code travels through the browser and the tokens travel only on the direct connection. PKCE ties the two halves together, so only the app that started the flow can finish it.
OAuth 2.0 authorization code flow with PKCE

The flow has two steps for a reason. The authorization code passes through the browser, where history, logs or another app might see it, so it is single-use and short-lived. Tokens travel only on the direct connection to the token endpoint.

A server-side web app is a confidential client and authenticates at the token endpoint with a client secret. Mobile and single-page apps are public clients that cannot keep a secret. PKCE (RFC 7636, 2015) fills that gap by proving the token request comes from the app that began the flow. Current guidance, in the OAuth security best practice (RFC 9700) and the OAuth 2.1 draft, is to use PKCE on every authorization code flow and to stop using the implicit and password grants. The state parameter protects the redirect against cross-site request forgery, and the authorization server must match redirect URIs exactly.

For machine-to-machine calls with no user, the client credentials grant gives a service a token of its own.

Access tokens, refresh tokens and OpenID Connect

An access token is short-lived and sent to the API on every call. A refresh token is long-lived, sent only to the authorization server to obtain new access tokens, and recorded server-side so it can be revoked. With refresh token rotation, each use returns a new refresh token and invalidates the old one. If an old one appears again, the server assumes theft and revokes the whole chain.

OAuth says what the app may do, not who the user is. OpenID Connect (2014) adds that layer. With the openid scope, the authorization server also returns an ID token: a JWT for the client, describing the user and the login. The ID token is for the app. The access token is for the API. “Sign in with Google” is OpenID Connect.

Authorization models

  • RBAC (role-based). Users have roles and roles have permissions. It is simple and easy to audit, but roles multiply when rules depend on context, such as “editor of project 42”.
  • ABAC (attribute-based). A policy is evaluated over attributes of the user, the resource, the action and the environment, often in a policy engine such as Open Policy Agent. It is flexible and harder to audit.
  • Relationship-based models derive access from relationships such as “owner of the folder that contains this document”. Google’s Zanzibar paper (2019) describes one at scale.

Whichever you choose, enforce it on the server for every request, and check access to the specific object, not only that the caller is logged in.

Service-to-service authentication

Between services there is no user to prompt. Common options are mutual TLS, where each service presents a certificate (see encryption), the client credentials grant, or signed requests. When a call is made on behalf of a user, pass the user’s identity in a verifiable token as well. A plain X-User-Id header can be set by anyone who can reach the service.

When to choose it and when not to

  • Server-side sessions suit a first-party web app on one domain that needs instant logout. They are the simplest safe default.
  • JWTs suit many services that must verify callers locally, and APIs used by mobile apps and third parties. Avoid them where you need instant revocation with no shared state, or as a place to keep session data.
  • OAuth and OpenID Connect suit third-party access, single sign-on and delegating login. A single app talking to its own backend does not need OAuth to function.

In the interview

In most designs one sentence is enough: users authenticate through an identity provider with OpenID Connect, the gateway validates tokens, and services enforce object-level authorization. Go deeper when the system is about identity, payments or sharing.

A strong answer in a minute: separate authN from authZ. Compare sessions and JWTs on revocation and lookup cost, then pick one for this system. If you choose JWTs, give the lifetime, the validation steps and the revocation plan. For third-party or mobile login, walk through the authorization code flow with PKCE and say what each parameter defends against.

Key takeaways

  • Authentication establishes who the caller is. Authorization decides what that caller may do. Design them separately.
  • Store passwords only as slow, salted hashes such as Argon2id or bcrypt, or avoid storing them by delegating login to an identity provider.
  • Server-side sessions are easy to revoke and need a lookup per request. JWTs verify locally and cannot be revoked before they expire without adding state back.
  • Validate a JWT by pinning the algorithm, then checking signature, issuer, audience and expiry. Never let the token choose its own algorithm.
  • The authorization code flow with PKCE keeps passwords away from the app and tokens out of the browser's address bar, and binds the code to the client that asked for it.
  • Keep access tokens short-lived and revoke through refresh tokens. OpenID Connect adds an ID token that says who logged in.

Check yourself

1. A user's laptop is stolen and they click "log out everywhere". The system uses self-contained JWT access tokens valid for 24 hours and keeps no server-side state. What happens?
2. What does the "alg confusion" class of JWT bugs exploit?
3. In the authorization code flow with PKCE, what stops an attacker who intercepts the authorization code from using it?
4. A single-page app receives an ID token and an access token after an OpenID Connect login. Which statement is correct?
5. An API checks that the caller is logged in, then returns the order whose id is in the URL. What is missing?

0 of 5 answered

Flashcards

These 6 cards are in your review deck. Tap a card to see the answer.

Authentication versus authorization?

Authentication answers "who are you?" and fails with 401. Authorization answers "are you allowed to do this?" and fails with 403.

How should passwords be stored?

As a slow, salted, memory-hard hash such as Argon2id, or bcrypt or scrypt, with a unique salt per user. Never in plaintext, reversibly encrypted, or with a fast hash such as SHA-256.

What are the three parts of a JWT?

A header (algorithm and key id), a payload of claims (iss, sub, aud, exp and others) and a signature, each base64url encoded and joined by dots. It is signed, not encrypted.

Name the four OAuth 2.0 roles.

Resource owner (the user), client (the app), authorization server (authenticates the user and issues tokens) and resource server (the API that accepts tokens).

What does PKCE add to the authorization code flow?

The client sends a hash of a random secret with the authorization request and the secret itself with the token request. Only the client that started the flow can redeem the code.

RBAC versus ABAC?

RBAC grants permissions through roles and is simple to audit. ABAC evaluates policies over attributes of the user, resource and context, which is more flexible and harder to reason about.

Review the deck