← Building blocks

Authenticate, then authorise

Security & abusefundamental

Who is calling, and are they allowed to do this?

Say it like this

Every request needs an identity and a permission check, so I authenticate once at the edge with short-lived signed tokens and authorise per resource inside the service that owns the data.

Basic solution

Authenticate with sessions or signed tokens (JWT) issued by an identity provider; authorise per resource with roles or policies at the service.

OAuth 2 / OIDCJWTsession cookiesRBAC / ABACAuth0 / Cognito

Short-lived token at the edge, ownership check at the data

Sign-in happens once at the identity provider. Every request carries a short-lived token the gateway verifies locally with a cached public key; the service that owns the row decides whether this subject may touch it.

How it works

  1. The user signs in with an identity provider, using a password plus multi-factor code or a social login through OIDC. The provider checks the credentials and issues two tokens: a short-lived access token (a JWT valid for 5 to 15 minutes) and a longer-lived refresh token.
  2. The client sends the access token in the Authorization header of every request. The gateway or service verifies the token's signature against the provider's public key, checks that it has not expired and that it was issued for this service (the audience claim), and reads out the subject (the user id) and the claims (roles, tenant). No database is consulted for this step.
  3. The request reaches the service that owns the resource. That service loads the resource and asks whether this subject is allowed to perform this action on this object. That question is authorisation, and it is answered from the resource's owner field, the user's role, or a policy engine.
  4. When the access token expires, the client sends the refresh token to the token endpoint and receives a new access token. The refresh token is where revocation lives: deleting it on the server ends the session as soon as the current access token runs out.
  5. Logout or a password change deletes the user's refresh tokens on the server. Any access token still in the wild keeps working until it expires on its own, which is why access tokens are kept to minutes.

Authentication vs authorisation

  • Authentication answers who you are. It happens once per request, cheaply, from the token alone.
  • Authorisation answers what you may do. It needs the resource, so it belongs in the service that owns the data, never only in the gateway.

Worked example

URL shortener creation API

  • 100M links/month created by 5M users; 40 writes/s. Redirects (4,000/s) are anonymous and skip auth entirely, which is the first thing to say: only the write path pays for it.
  • Access token: a JWT with sub, tenant, scopes, exp. About 400 bytes. Verifying an RS256 signature costs roughly 20 to 50 microseconds; an ES256 one about twice that, because ECDSA is cheap to sign but slower to verify. At 40 writes/s this is nothing; at 40K/s it is still only a few CPU-seconds per second across the fleet.
  • Token lifetime 10 minutes, refresh token 30 days. A compromised access token is useful for at most 10 minutes; a stolen refresh token until it is rotated, so refresh tokens are one-use and rotate on every refresh.
  • Authorisation check on DELETE /v1/urls/{alias}: load the row (one indexed read), compare row.user_id with token.sub, or allow if the token carries the admin role. No extra round trip; the data needed is the row itself.
  • Public key cache: services fetch the provider's JWKS once and cache for an hour, so verification needs no network call. A key rotation publishes the new key alongside the old one for a day.

Variants and when each wins

Stateful sessions (cookie + server-side session store)

  • The browser holds a random session id in an HttpOnly cookie, and each request looks that id up in Redis. It wins for a single web app talking to its own backend, because revocation is instant (delete the row) and the cookie carries nothing readable; it costs one cache lookup per request and a shared store.

Stateless JWT

  • The token carries the claims plus a signature, so any service verifies it locally. It wins when many services or domains must verify identity without a shared store; it cannot be revoked before expiry, so keep it short and pair it with a revocable refresh token.

OAuth 2 / OIDC with an identity provider

  • Sign-in is delegated to Auth0, Cognito, Okta or your own provider, and your services only verify tokens. It wins by removing password handling from your code; the provider becomes a dependency whose outage blocks new logins, though already-issued tokens keep working.

Role-based vs attribute-based authorisation

  • RBAC gives users roles and roles grant actions; ABAC and policy engines (OPA, Cedar) evaluate rules over attributes of the user, the resource and the context. RBAC wins for most products because it is simple; ABAC wins once you need tenant isolation, ownership checks or time-based rules that a role cannot express.

Recommendation: OIDC with short JWT access tokens and rotating refresh tokens; sessions in a cookie for a single web app; RBAC until a rule cannot be expressed as a role.

Failure modes

Token cannot be revoked

  • A banned user, or one who just changed their password, keeps working for a while. It happens because a JWT is valid until its expiry regardless of what the server now thinks. Keep access tokens to 5 to 15 minutes, revoke refresh tokens, and keep a small deny list of token ids for the rare emergency.

Authorisation only at the gateway

  • A user reads another user's link by guessing its id. It happens because the gateway verified the token but nobody checked who owns the resource. Have every service compare the token subject against the resource it loads, and test it with a second user in integration tests.

Long-lived or over-scoped tokens

  • One leaked token exposes everything for months. It happens because long expiry and broad scopes were convenient. Issue scopes per client, use short expiry, rotate refresh tokens on every use, and bind tokens to the client where the platform allows it.

Identity provider outage

  • Nobody can log in, while existing sessions keep working. It happens because the provider sits on the login path by design. Accept that trade-off, cache the provider's public keys (JWKS) so verification continues, and keep access tokens valid through a short outage.

Token in the wrong place

  • Tokens turn up in server logs, referrer headers and browser history. It happens because they were put in query strings, or in localStorage where any script on the page can read them. Send tokens in the Authorization header for APIs, use HttpOnly SameSite cookies for browsers, and redact authorisation headers in logs.

Interviewer follow-ups

Answer out loud before you open each one.

JWT or session cookie for a web app, and why?

For a single web app talking to its own backend, a session cookie is simpler and revocable instantly, with one Redis lookup per request. JWTs win when many services or domains must verify identity without a shared store. Many systems use both: a session for the browser, a JWT minted from it for service-to-service calls.

How do you log a user out everywhere immediately with JWTs?

Delete all their refresh tokens so no new access tokens can be minted, and bump a per-user token version stored in a cache; verification compares the token version claim with the cached value. That turns a stateless check into one cache read, which is acceptable for the rare case where instant logout matters.

Where does the authorisation check live for "delete this link"?

In the URL service, after loading the row: the token subject must equal the owner or carry an admin role. The gateway cannot do it because it does not know who owns alias aB3xZ9. Putting the check next to the data also means the rule is enforced for every caller, including internal ones.

How do you rotate the signing key without logging everyone out?

Publish the new public key in the JWKS alongside the old one, start signing with the new key, and keep the old key published until every token signed with it has expired. Services identify the key by the kid header. Only refresh tokens, which are stored, need no rotation handling.

Connections

Pairs with
Identify API clients · One front door for many services · Limit requests per client · Protect data and secrets · Terminate TLS at the edge
Pulls against
Decide what happens when a guard is down

The same parts on other clouds

The diagrams above name AWS services as one concrete example. Every part has a close equivalent elsewhere. In an interview, name the role first, such as “a managed Redis cache”, then the product you would pick.

AWSUsed here asGoogle CloudMicrosoft AzureOpen source and others
Amazon CognitoIdentity providerIdentity PlatformMicrosoft Entra External IDAuth0, Okta, Keycloak
Amazon API GatewayAPI gatewayAPI Gateway, ApigeeAPI ManagementKong, Tyk
Amazon EC2 Auto ScalingURL serviceCompute Engine managed instance groupsVirtual Machine Scale SetsKubernetes Deployment with a HorizontalPodAutoscaler, Nomad
Amazon AuroraURL storeAlloyDB for PostgreSQL, Cloud SQLAzure Database for PostgreSQL or MySQLPostgreSQL, MySQL, CockroachDB
Amazon DynamoDBRefresh token storeFirestore, BigtableCosmos DBScyllaDB, Apache Cassandra