SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
  • Rate Limiting
  • Authentication vs Authorization
  • Session vs Token Based Auth
  • JWT
  • OAuth / OAuth2
  • Single Sign-On (SSO)
  • API Keys
  • OpenID Connect (OIDC)
  • CSRF
  • Input Validation
  • mTLS and Request Signing (HMAC)
Part 3: Caching
Part 4: Data and Storage
Part 5: Architecture
Part 6: Distributed Systems
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/APIs and Communication/API Security

OpenID Connect (OIDC)

The login layer on top of OAuth2: it tells an app who the user is.

⏱ 14 min readIntermediateMust KnowInterview FavouriteHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

OpenID Connect (OIDC) is a thin login layer on top of OAuth 2.0. OAuth answers “what may this app do?”. OIDC adds the missing answer to “who just logged in?”.

  • The app asks for the special scope openid. Along with the access token, it also gets an ID token.
  • The ID token is a signed JWT with claims about the user and the login: who (sub), who issued it (iss), who it is for (aud), when it ends (exp).
  • The app must validate the ID token. The access token is for calling APIs, not proof of identity.

02Concept: What is it?

OAuth 2.0 was designed to give an app access to something. It never promised to tell the app who the user is. Many apps used OAuth for login anyway, each in its own way, and that led to bugs and attacks.

OIDC fixes this by standardising login. It reuses the OAuth flows, and adds a few things: the openid scope, the ID token, a UserInfo endpoint for more profile data, and a discovery document so apps can configure themselves.

OAuth 2.0 and OIDC side by side
OAuth 2.0 alone
🔑Access tokenwhat the app may do
❓Who is the user?not defined
OAuth 2.0 + OIDC
🔑Access tokenwhat the app may do
🪪ID tokenwho logged in, and how
OIDC does not replace OAuth. It sits on top of it and reuses its flows.

What is inside an ID token?

It is a JWT with three parts (header, payload, signature). The payload holds claims. These are made-up example values:

ID token payload (example)
{
  "iss": "https://login.example.com",   // who issued it
  "sub": "user-8421",                   // the user's stable id
  "aud": "my-app",                      // the app it was made for
  "exp": 1767225600,                    // when it stops being valid
  "iat": 1767225300,                    // when it was issued
  "nonce": "n-7f3a",                    // ties it to one login attempt
  "email": "ada@example.com"            // optional profile claim
}
🧠Two tokens, two jobs
The ID token is meant for the app: it says who logged in. The access token is meant for the API: it says what the app may do. Do not send the ID token to APIs as a key, and do not read the access token as proof of identity.

03Real-Life Example

🍵The Hotel Front Desk
You arrive at a hotel (the app). Instead of keeping your passport, the hotel trusts the passport office (the identity provider). You go to the office’s counter, show your passport there, and get a sealed card with your name, a stamp and an expiry date. The hotel checks the seal, checks the card is for this hotel, checks it is not out of date, and checks it was issued for today’s visit. If all is well, you get a room key.
Hotel
OpenID Connect
The hotel
The app (relying party)
The passport office
The identity provider (OP)
Showing the passport at the office
The user logs in on the provider’s page
The sealed card with a stamp
The ID token (a signed JWT)
Checking the stamp is real
Verifying the signature with the provider’s public keys
“This card is for this hotel”
Checking the aud claim
“Not out of date”
Checking the exp claim
“Issued for today’s visit”
Checking the nonce
The room key
The app’s own session
Login with an identity provider
🧑User
→↓log in
🏛️Identity providerchecks you
→↓ID token
📱Appvalidates, starts session

04Why Do We Need It?

🧭One standard way to log in
Every provider and every library speaks the same language. No custom code for each one.
🙈No passwords in your app
The user logs in on the provider’s page. Your app never sees or stores the password.
🪪A clear answer to “who?”
The ID token has a stable user id (sub), so you do not guess from an email address.
🔁Single sign-on
One login at the provider can open many apps, with one place for MFA and passkeys.
🧰Self-configuring
A discovery document and published keys let a client set itself up from one URL.
🛡️Safer than home-made login
State, nonce and PKCE are built in to stop replay and code-stealing attacks.
OAuth gives your app a key. OIDC gives your app a verified name tag. Use OIDC whenever the question is “who is this user?”.

05Where Do We Use It?

🔘“Log in with Google / Microsoft / Apple”
Social logins are OIDC (or OIDC-compatible) in most cases.
🏢Company single sign-on
Providers such as Okta, Microsoft Entra ID, Auth0 and Keycloak offer OIDC for work apps.
📱Mobile and single-page apps
The authorization code flow with PKCE is the usual choice for apps that cannot keep a secret.
☸️Kubernetes and cloud consoles
Many platforms let you log in to clusters and consoles through an OIDC provider.
🧩Microservices behind a gateway
A gateway signs the user in with OIDC, then passes identity on to the services.
🤝Federation between companies
Partners trust each other’s identity providers instead of making new accounts.

06Types / Parts / How It Works

The parts of OIDC

PartWhat it isWhy it matters
openid scopeA special scope the app adds to the requestTells the provider “this is a login”, so an ID token is returned.
ID tokenA signed JWT about the loginThe proof of who logged in. Validated by the app.
UserInfo endpointAn API that returns profile claims for an access tokenKeeps the ID token small. Use it for extra details.
Discovery documentJSON at /.well-known/openid-configurationLists the endpoints and the key location, so setup is automatic.
JWKSThe provider’s public signing keys, as a JSON setUsed to check the ID token signature. Keys rotate over time.
Standard scopesprofile, email, address, phoneAsk only for the claims you really need.

Which flow to use

The authorization code flow with PKCE
📱Appstate, nonce, PKCE
→↓redirect
🏛️Provideruser logs in
→↓code
📱Appswaps code + verifier
→↓tokens
🪪ID + access token
App Provider Tokens
Recommended for web, single-page and mobile apps. The browser only carries a short-lived code. The tokens come back on a direct, back-channel call.
FlowUse it?Notes
Authorization code + PKCEYes, the defaultWorks for server apps, single-page apps and mobile apps.
Authorization code (with a client secret)Yes, for server-side appsThe secret stays on your server, never in browser or mobile code.
Implicit flowNo, avoidReturns tokens in the browser address bar. Older and weaker. Replaced by code + PKCE.
Password grantNo, avoidThe app handles the user’s password. This is what OAuth was made to prevent.
VisualizerLogin step by step, and which check rejects a bad ID tokenPress Next through the seven steps. Then pick Wrong audience, Expired or Nonce mismatch, and see which validation fails at step 6.
What does the ID token look like?
The provider signs a fresh ID token made for this app, and it carries the nonce this app created.
📱Appmakes state, nonce, PKCE
→↓start
🌐Browseruser clicks Log in
Step 1 of 7
1. The app starts the login
The app creates three random values: state (to match the reply to this request), nonce (to match the ID token to this login) and a PKCE secret (code_verifier). It keeps them, and sends only the hash of the PKCE secret.

A simplified teaching model. Names, addresses and values are made-up examples. Real providers add more checks, such as the issued-at time, the signing algorithm and the key id.

07How to Use It / Steps / Implementation

Adding “Log in with …” to an app

  1. 1
    Register the app
    At the provider, create a client. Set the exact redirect URI. You get a client id (and a client secret for a server-side app).
  2. 2
    Read the discovery document
    Fetch /.well-known/openid-configuration. It gives you the authorization, token, UserInfo and key endpoints, so you do not hard-code them.
  3. 3
    Start the login
    Create state, nonce and a PKCE code_verifier. Redirect with scope=openid (plus profile or email if needed), the code_challenge and the redirect URI.
  4. 4
    Handle the callback
    Check the state matches the one you saved. Take the code from the URL, and do not trust anything else in it.
  5. 5
    Swap the code for tokens
    Call the token endpoint directly from your server (or app), with the code and the code_verifier.
  6. 6
    Validate the ID token
    Check the signature using the provider’s keys, then iss, aud, exp and nonce. Use a well-tested library for this.
  7. 7
    Start your own session
    Use sub (with iss) as the stable user id. Create your normal session or cookie. Call the UserInfo endpoint only if you need more profile data.
⚠️Always check these claims
iss must be the provider you expect. aud must contain your client id. exp must be in the future. nonce must match the one you created. A valid signature alone is not enough. A correctly signed token made for another app must still be refused.
💡Use a library
Do not write signature and claim checking by hand. Use a maintained OIDC library for your language, and keep it updated.

08Key Terms to Know

TermMeaning in easy words
OpenID Connect (OIDC)A login standard built on top of OAuth 2.0
Identity provider (OP)The service that logs the user in and issues tokens (Okta, Google, Keycloak)
Relying party (RP)The app that relies on the provider to know who the user is
ID tokenA signed JWT that says who logged in and how. Meant for the app
Access tokenA token used to call APIs. Not proof of identity
ClaimOne fact inside a token, such as sub, email or exp
subThe user’s stable, unique id at that provider
NonceA random value that ties an ID token to one login attempt, to stop replay
PKCEA one-time secret that stops a stolen authorization code from being used
Discovery documentA JSON file listing the provider’s endpoints and settings
JWKSThe provider’s set of public keys used to check token signatures

09Pros, Cons and Trade-offs

✅ Pros
  • One standard, many providers
  • No passwords stored in your app
  • Works with single sign-on and MFA at the provider
  • Built-in protection against replay and code theft
  • Good libraries in every language
⚠️ Cons
  • More moving parts than a simple form login
  • Easy to get wrong without a library (skipped claim checks)
  • You depend on the provider being up
  • Key rotation and clock differences need care
  • Logout and session sync across apps are tricky

Trade-offs

ChoiceWe gainWe lose
OIDC provider (hosted)Security work, MFA and passkeys done for youAnother vendor, cost and an outside dependency
Run your own provider (Keycloak etc.)Full control of data and settingsYou run, patch and secure a critical service
ID token onlySimple, no extra callsToken may be large or lack the claims you need
ID token + UserInfoFresh and detailed profile dataOne more network call per login
Short token lifetimeA stolen token is useful for less timeMore refreshes and more load on the provider

10Common Problems and Mistakes

Common mistakes

  1. Using the access token to identify the user. It was made for an API. A token for another app’s API could be used to impersonate a user.
  2. Skipping the aud or iss check. A valid token for a different app or a fake issuer gets accepted.
  3. Not checking the nonce and state. Opens the door to replay and login-CSRF attacks.
  4. Matching users by email only. Emails can change or be reused. Use iss + sub as the key.
  5. Using the implicit flow or putting tokens in URLs and logs.
  6. Loose redirect URIs. Wildcards let an attacker steal the code. Register exact URIs.
  7. Putting a client secret in a mobile or browser app. Anyone can extract it. Use PKCE instead.

Things to watch

🔄Key rotation
Providers rotate signing keys. Cache the JWKS, and re-fetch when you see an unknown key id.
⏱️Clock skew
Servers’ clocks differ a little. Allow a small leeway when checking exp and iat, but not minutes.
🚪Logout
Logging out of your app does not log the user out of the provider. Decide what you want, and test it.
🧾Token size and privacy
Ask for the fewest claims you need. Do not store the ID token longer than necessary.

11Real-World Examples

🔘Social login buttons
Sign-in buttons on many sites use OIDC under the hood.
🏢Workforce SSO
Employees log in once to a company provider and open many internal tools.
☁️Cloud identity
Cloud platforms let workloads and people sign in with OIDC identities from other providers.
🚢Kubernetes login
Clusters can trust an OIDC provider so that users sign in with their company account.
🤖CI/CD to cloud
Build systems can present short-lived OIDC tokens instead of storing long-lived cloud keys.
🛍️Customer sign-in
Shops and apps outsource login to a customer identity service built on OIDC.
📝Note
Provider names, endpoints and supported features change between products and versions. Use the provider’s own documentation for exact settings.
Mini case: one company login for three apps
🧑Employee
→↓logs in once
🏛️Company providerMFA lives here
→↓ID tokens
📊Dashboard
🧾Expenses
📚Wiki
User Provider Apps
The apps never see the password. Each validates its own ID token.

12Related Topics to Read Next

OAuth / OAuth2→

OIDC is built on top of it and reuses its flows.

JWT→

The ID token is a JWT, so signing and claims apply.

Single Sign-On (SSO)→

OIDC is a common way to deliver SSO.

Authentication vs Authorization→

OIDC is authentication. OAuth is authorization.

SAML→

The older, XML-based way to do enterprise login.

CSRF→

State and nonce protect the login flow from forged requests.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • ✔What: OIDC = OAuth 2.0 + a standard way to say who logged in.
  • ✔New things: openid scope, ID token (JWT), UserInfo, discovery, JWKS.
  • ✔Two tokens: ID token is for the app (who). Access token is for the API (what).
  • ✔Flow: authorization code + PKCE for web, SPA and mobile.
  • ✔Validate: signature, iss, aud, exp, nonce (and check state on the callback).
  • ✔User key: iss + sub, never just the email.
  • ✔Avoid: implicit flow, wildcard redirect URIs, client secrets in public apps.
  • ✔One line: “OAuth hands out the key. OIDC checks the name tag.”
← Previous
API Keys
Next →
CSRF