Course contents

12. Security and Identity Lesson 5 of 8

OpenID Connect

How OIDC adds sign-in to OAuth 2.0: the ID token, discovery and JWKS, state, nonce and PKCE, UserInfo, and keeping the provider off the request path.

16 minIntermediate10 steps
Loading the interactive simulation…
Loading the knowledge check…

Summary

  • OIDC is an identity layer on OAuth 2.0: the provider issues a signed ID token that says who signed in, to which app, and when.
  • Use the authorization code flow with PKCE; state protects the redirect, nonce binds the ID token to this sign-in.
  • Validate the ID token locally with cached discovery data and JWKS: signature, iss, aud, exp, nonce. Key users by iss + sub.
  • ID tokens are for the client; access tokens are for APIs, UserInfo included.
  • After sign-in, run your own session: the provider should be needed for sign-ins, not for every request.
Deep diveHow it works, trade-offs, failure modes, misconceptions and the interview angle.

What it is

OpenID Connect (OIDC) is an identity layer on top of OAuth 2.0. OAuth lets an application get an access token to call an API on a user's behalf. OIDC adds a second artefact, the ID token: a signed JSON Web Token in which the OpenID Provider (OP: Entra ID, Okta, Auth0, Keycloak, Google and so on) states that a particular user signed in, for a particular application (the relying party, RP), at a particular time. It also standardizes discovery, a UserInfo endpoint, scopes for profile claims, and logout.

Why it exists

Before OIDC, many sites "logged in with OAuth": they took an access token, called some profile API, and trusted whatever user id came back. Access tokens are not addressed to the client, so a token that a user had granted to any app could be replayed at another app to sign in as that user (token substitution). Every provider also invented its own profile API. OIDC fixes both: the ID token is addressed to one client (aud), bound to one sign-in (nonce) and verifiable offline, and the protocol is the same at every provider.

How it works

Discovery. The RP reads https://<issuer>/.well-known/openid-configuration once and caches it: the issuer identifier, authorization, token and UserInfo endpoints, supported algorithms, and jwks_uri, where the provider publishes its public signing keys as a JSON Web Key Set. Each key has a kid.

Authorization code flow with PKCE (the recommended flow for web, mobile and single-page apps; the implicit flow is deprecated by the OAuth 2.0 Security Best Current Practice, RFC 9700):

  1. The RP redirects the browser to the authorization endpoint with response_type=code, scope=openid (plus email, profile…), client_id, redirect_uri, state, nonce and a PKCE code_challenge (S256). It stores state, nonce and the code_verifier in a short-lived cookie or server-side.
  2. The user authenticates at the provider. The RP never sees the password or passkey.
  3. The provider redirects back to redirect_uri with a one-time code and the same state. The RP checks state.
  4. The RP calls the token endpoint server-to-server with the code, the code_verifier and its client authentication (secret, private_key_jwt client assertion, or mTLS). It receives an ID token, an access token and often a refresh token.

ID token validation, done locally: verify the signature with the JWKS key named by kid, accepting only the algorithms you expect (never none); iss equals the discovered issuer exactly; aud contains your client_id (and azp is you if there are several audiences); exp is in the future, with small clock skew; nonce equals the stored value. Optionally check auth_time or acr/amr when you require recent or multi-factor authentication. The user's identity is the pair iss + sub.

UserInfo. With the access token, the RP can call the UserInfo endpoint for claims not in the ID token. The sub must match the ID token's.

After sign-in the RP creates its own session (a cookie, see Session-Based Authentication). It can renew claims with the refresh token, and learn about sign-outs through RP-initiated logout, front-channel or back-channel logout.

When to use it

  • Signing users in with a corporate or social identity provider, or single sign-on across your own apps.
  • Any time an app needs to know who the user is, rather than only call an API on their behalf.
  • Federating identity between organizations (B2B customers bringing their own IdP).
  • Workload identity federation also reuses OIDC tokens: CI systems and Kubernetes clusters issue OIDC tokens that clouds accept in exchange for short-lived credentials (see Secrets Management).

When not to

  • Machine-to-machine calls with no user: use OAuth client credentials (or mTLS / workload identity). There is no one to sign in.
  • A single app with its own user database and no federation needs: a local login plus sessions is simpler, though many teams still prefer a hosted provider to avoid storing credentials.
  • Authorization decisions: OIDC tells you who the user is. What they may do is still your application's job.

Trade-offs

Choice You gain You pay
Hosted provider instead of your own login MFA, passkeys, breach detection, federation Vendor dependency and cost; sign-in fails when it is down
Local ID token validation No network call, works during provider hiccups Must handle key rotation; revocation is only noticed on refresh
Short app sessions Faster reaction to disabled accounts More redirects or refreshes against the provider
Calling UserInfo per request Always-fresh claims A remote round trip on every request; provider outage = your outage
Fat ID tokens (many claims) Fewer UserInfo calls Larger cookies or headers, more personal data spread around

Alternatives

  • SAML 2.0: XML-based enterprise federation, still common for workforce SSO. Heavier, browser-centric, no native mobile story.
  • Plain OAuth 2.0 plus a profile API: what OIDC replaced. Avoid for sign-in.
  • Passkeys (WebAuthn) directly in your app: strong authentication without a federation protocol; you still own the account store.
  • Session-only login with a local password store: fine for small apps, but you carry credential storage and MFA yourself.

Failure modes

  • Accepting access tokens as login proof: token substitution, as in step 1.
  • Skipping aud or nonce checks: tokens issued to other clients, or replayed tokens, are accepted.
  • Algorithm confusion: accepting alg: none or verifying an RS256 token as HS256 with the public key as the HMAC secret. Pin the expected algorithms.
  • Keying users by email: emails change and can be reassigned; some providers let users set unverified emails. Use iss + sub.
  • Key rotation outages: a cached JWKS without a refresh path rejects every token after rotation. Refresh on unknown kid, rate-limited.
  • Provider on the request path: calling UserInfo or introspection per request couples every page view to the provider's latency and availability (steps 8–9).
  • Open redirects: loosely matched redirect_uri values let attackers receive codes. Register exact redirect URIs.

In production

Use a maintained OIDC client library rather than parsing tokens by hand. Register exact redirect URIs, use PKCE for every client, and prefer asymmetric client authentication (private_key_jwt) over shared secrets for confidential clients. Cache discovery and JWKS, refresh on unknown kid. Keep tokens server-side where possible (a backend-for-frontend holds tokens and gives the browser only an HttpOnly session cookie). Implement back-channel logout if you need sessions to end when the provider session ends. Monitor sign-in error rates separately from request error rates.

Common misconceptions

  • "OAuth is an authentication protocol." OAuth is delegated authorization. OIDC is the authentication layer on top.
  • "The ID token is a bearer token for my APIs." It is addressed to the client. APIs take access tokens issued for them.
  • "Validating a token means calling the provider." ID tokens and JWT access tokens are verified locally with the published keys; only opaque tokens need introspection.
  • "PKCE makes state and nonce unnecessary." They protect different steps; keep them.
  • "Sign-out at the app signs the user out everywhere." Only with RP-initiated logout at the provider plus logout propagation to other apps.

Interview angle

Expect to draw the authorization code flow with PKCE, say which values travel through the browser (code, state) and which do not (tokens, verifier), and list the ID token checks. Strong answers distinguish ID token from access token, explain token substitution and why aud and nonce exist, handle JWKS rotation, and keep the identity provider off the hot path with an application session, while being clear that new sign-ins still depend on it.

Model assumptions

Steps 1–7 are a scripted illustration, not a simulation: redirects, the code exchange, token validation and the attacks are drawn as hand-placed packets with illustrative durations (10 ms between the browser and the app, 15 ms to the provider). The engine has no notion of tokens, signatures or redirects. Steps 8–10 use the simulation: Poisson arrivals at 200 page views per second, a notes app with 32 workers and 4 ms mean service time (lognormal, cv 0.3), a database with 16 connections and 3 ms reads 1 ms away, and in step 8 a UserInfo endpoint with 16 workers and 5 ms per call, 15 ms away. A provider that is down refuses connections and the app fails the request. That gives about 64 ms per page view with UserInfo on the path and about 29 ms without it. Numbers are illustrative, not benchmarks of any provider.

The lesson as textEvery step of the simulation, written out.
  1. 1. An access token is not a login

    OAuth 2.0 lets an app act on a user’s behalf: it gets an access token meant for an API. It says nothing the *app* can rely on about who signed in, when, or for which app the token was issued.

    Apps that "log in with OAuth" anyway get tricked. A malicious app that Alice once used holds an access token issued to *it*. It presents that token to the Notes App, the Notes App asks the provider "whose token is this?", hears alice, and logs the attacker in as Alice. This step is a scripted illustration: the packets are placed by hand.

    Scene: A malicious app presents an access token that was issued to it for Alice. The Notes App asks the provider who the token belongs to, hears Alice, and logs the attacker in as Alice.

    Key idea: OAuth answers "may this app call the API?", not "who just signed in to this app?".

  2. 2. Discovery: learn the provider’s endpoints and keys

    OpenID Connect (OIDC) is a thin identity layer on top of OAuth 2.0. The app (the relying party, RP) starts by reading the provider’s discovery document at /.well-known/openid-configuration: the issuer name, the authorization, token and UserInfo endpoints, and jwks_uri.

    It then fetches the JWKS, the provider’s public signing keys, each with a key id (kid). Both are cached: they change rarely, and the keys let the app verify tokens without calling the provider again.

    Scene: The Notes App fetches the provider’s discovery document, then its public signing keys (JWKS), and caches both.

    Key idea: Discovery and JWKS are fetched once and cached; they make token verification a local operation.

  3. 3. The browser is sent to the provider

    Alice clicks *Sign in*. The app answers with a redirect to the authorization endpoint: response_type=code, scope=openid email profile, its client_id and redirect_uri, plus three one-time values it also stores in Alice’s pre-login cookie: state (ties the answer to this browser, against CSRF), nonce (will be copied into the ID token) and a PKCE code_challenge.

    Alice authenticates at the provider (passkey, password + MFA). The app never sees her password. The provider redirects back to the app’s callback with a short-lived authorization code and the same state.

    Scene: The browser asks the app to sign in, is redirected to the provider, Alice authenticates there, and the provider redirects the browser back to the app with an authorization code.

    Key idea: Authorization code flow: the browser only ever carries a one-time code, bound by state, nonce and PKCE.

  4. 4. Trade the code for tokens on the back channel

    The app checks that state matches the cookie, then calls the token endpoint directly, server to server: the code, the PKCE code_verifier, and its client authentication (a client secret, or better, a signed client assertion or mTLS).

    The provider answers with an ID token (a signed JWT about the sign-in, addressed to this app), an access token (for APIs such as UserInfo) and often a refresh token. Nothing of value travelled through the browser’s address bar.

    Scene: The app sends the code and the PKCE verifier to the provider’s token endpoint and receives an ID token and an access token.

    Key idea: Tokens come over the back channel; the ID token is for the app, the access token is for APIs.

  5. 5. Validate the ID token locally

    The app validates the ID token without calling anyone: the signature with the cached JWKS key named by kid (and only the algorithm it expects, never none); iss equals the discovered issuer; aud contains its own client_id; exp is in the future; nonce equals the value in Alice’s pre-login cookie.

    Only then does sub (the provider’s stable id for Alice, unique per issuer) become the app’s user. The app creates its own session and sets a cookie. Use iss + sub as the key, not the email address: emails change and can be reassigned.

    Scene: The app checks the ID token’s signature against its cached keys and its issuer, audience, expiry and nonce, then answers the browser with its own session cookie. Nothing is sent to the provider.

    Key idea: Check signature, iss, aud, exp and nonce; identify the user by iss + sub.

  6. 6. The same attacks now bounce off

    The malicious app tries again. First it hands over an ID token it received for Alice. Its aud is other-app, not notes-app: rejected.

    Then it replays a genuine Notes App ID token it captured from an earlier sign-in, injected into a callback. Its nonce does not match the one in the attacker’s own pre-login cookie: rejected. Neither check needed a call to the provider. This is why the ID token, not an access token, is the proof of sign-in.

    Scene: The malicious app sends an ID token issued to another app, which the Notes App rejects because of its audience, then a replayed Notes App ID token, which it rejects because the nonce does not match.

    Key idea: aud stops tokens issued to other apps; nonce stops replayed tokens.

  7. 7. UserInfo: more claims, with the access token

    Some claims (address, a fresh picture URL) may not be in the ID token. The app can call the UserInfo endpoint with the *access token* and get them as JSON. The sub in the answer must equal the ID token’s sub.

    Keep the tokens apart: the ID token is for the app that requested it and is never sent to APIs; access tokens go to APIs (UserInfo is one). Do this once at sign-in, or when claims need a refresh, not on every page view.

    Scene: The app calls the provider’s UserInfo endpoint with the access token and gets Alice’s profile claims back.

    Key idea: ID token → the client. Access token → APIs, including UserInfo.

  8. 8. Asking the provider on every page view

    Now the simulation runs: 200 page views per second. This version of the app does not keep a session. On every request it calls UserInfo to "check the user is still signed in", then loads the notes.

    Every page view pays an extra round trip to the provider: about 64 ms instead of 29 ms here. Worse, at 1.5 s the provider goes down and every page view fails: the identity provider has become a dependency of every request, for every user already signed in.

    Scene: Users send 200 page views per second. The app calls the provider’s UserInfo endpoint, then the notes database, on every request, at about 64 ms. After 1.5 seconds the provider goes down and every request fails.

    Key idea: Calling the provider per request turns sign-in infrastructure into a runtime dependency.

  9. 9. Validate once, then use the app’s own session

    The app does what step 5 described: it validates the ID token once at sign-in and from then on checks its own session cookie, locally. The call to the provider disappears from the request path; page views are back to about 29 ms.

    The provider fails again at 1.5 s, and signed-in users notice nothing. New sign-ins would fail until it is back, which is a much smaller outage. The app re-checks with the provider on its own schedule: when the session ages out, via a refresh token, or when the provider sends a back-channel logout. If a token arrives with an unknown kid, the app re-fetches the JWKS (the provider rotated its keys).

    Scene: Users send 200 page views per second; the app checks its own session and reads the notes database, at about 29 ms. The provider goes down after 1.5 seconds and no request fails.

    Key idea: Sign-in needs the provider; serving signed-in users should not.

  10. 10. OpenID Connect in one picture

    OIDC adds an ID token to OAuth 2.0: a signed statement from the provider that a user signed in, addressed to one app and bound to one sign-in by the nonce. Use the authorization code flow with PKCE, state and nonce; get tokens on the back channel.

    Validate the ID token locally with cached discovery data and JWKS, key users by iss + sub, keep ID tokens out of API calls, and run your own session after sign-in so the provider is not on every request.

    Scene: Users send 200 page views per second to the app, which serves them from its own sessions and the notes database. The provider is up and off the request path.

    Key idea: Redirect for the code, exchange it on the back channel, validate locally, then run your own session.