Appearance
OpenID Connect
93. What is OpenID Connect (OIDC), and why was it introduced?
The short answer
OpenID Connect is a thin identity layer on top of OAuth 2.0, published in 2014. OAuth only says what an app may do, not who the user is, so every company built its own "log in with OAuth" on top, many with security holes. OIDC standardised the missing piece: add openid to the scopes, and alongside the access token you receive an ID token, a signed JWT that says who logged in, at which provider, for which app, and when. It also standardised user profile claims, a UserInfo endpoint, automatic configuration discovery and logout.
What OIDC adds to OAuth:
| Piece | What it gives you |
|---|---|
openid scope | Turns an OAuth request into an OIDC login |
| ID token | A standard, verifiable statement of who logged in |
| Standard claims | sub, email, email_verified, name, picture and more |
| UserInfo endpoint | Fetch profile claims with the access token |
| Discovery | One URL describes every endpoint and setting of the provider |
| JWKS | Published signing keys, rotated by kid |
| Logout specs | RP-initiated, front-channel and back-channel logout |
94. What is the difference between OAuth 2.0 and OIDC?
The short answer
OAuth 2.0 is for authorization: it gives an app an access token to call an API on the user's behalf. OIDC is for authentication: it uses the same flows, but adds an ID token that tells the app who the user is. Ask for openid and you are doing OIDC; ask for only API scopes and you are doing plain OAuth. "Sign in with Google" is OIDC. "Allow this app to read your Google Drive" is OAuth. A single request can do both.
| OAuth 2.0 | OpenID Connect | |
|---|---|---|
| Purpose | Delegated access to APIs | Logging the user in |
| Main output | Access token | ID token, plus an access token |
| Token audience | The API | Your app, the client |
| Format | Not specified | ID token is always a JWT |
| User info | Not specified | Standard claims and UserInfo endpoint |
| Scopes | Defined by each API | openid, profile, email, address, phone |
95. What is an ID Token?
The short answer
An ID token is a signed JWT issued by the OpenID provider to your app, stating that a user logged in. Its key claims: iss, the provider; sub, the user's permanent ID at that provider; aud, your client_id; exp and iat; auth_time, when the user actually authenticated; nonce, echoing the random value you sent, to stop replay; and often email, email_verified and name. Your app verifies it once at login, then creates its own session. It is not for calling APIs.
json
{
"iss": "https://accounts.google.com",
"sub": "110169484474386276334",
"aud": "1234987819200.apps.googleusercontent.com",
"exp": 1793004500,
"iat": 1793000900,
"auth_time": 1793000890,
"nonce": "n-0S6_WzA2Mj",
"email": "asha@example.com",
"email_verified": true,
"amr": ["pwd", "mfa"]
}What your app must check, in order:
- Signature, with the provider's key from its JWKS, using only the algorithms you expect.
issequals the provider you started the login with.audcontains your ownclient_id. A token issued to another app must be rejected.expis in the future.nonceequals the value you stored in the session for this login.auth_timeis recent enough, if you asked for a fresh login withmax_age.
Identify users by iss plus sub. sub never changes for a user at that provider, while email can. Two providers can both have a sub of 12345, so store the pair.
96. What is the difference between an ID Token and an Access Token?
The short answer
The ID token is for your app: it tells you who logged in, its audience is your client_id, and you read and verify it. The access token is for an API: it grants permission to call that API, its audience is the API, and your app should treat it as opaque. Never send an ID token to an API as authorisation, and never use an access token as proof that a user logged in to your app. Mixing them up is one of the most common OIDC mistakes.
| ID token | Access token | |
|---|---|---|
Audience, aud | Your client | The resource server, the API |
| Read by | Your app | The API |
| Format | Always a JWT | JWT or opaque |
| Proves | Who logged in, when, how | What the holder may do |
| Sent to APIs | Never | Yes, as Bearer |
| Lifetime | Used once at login | Minutes, refreshed |
A memorable rule. The ID token is a receipt for your app: "Asha logged in at 10:02 with MFA". The access token is a key for the API: "may read orders". You keep the receipt; you hand the key to the door.
97. What is the OIDC UserInfo endpoint?
The short answer
UserInfo is an endpoint on the OpenID provider that returns claims about the user, such as name, email, picture and locale, when called with an access token that includes the openid scope. It is useful when the ID token was kept small, when you need fresh profile data later, or when claims are too large for a token. Always check that the sub from UserInfo matches the sub in the ID token, so a mixed-up or substituted response cannot attach the wrong profile to the user.
http
GET /userinfo HTTP/1.1
Host: auth.shop.example
Authorization: Bearer eyJhbGciOiJSUzI1NiIs…json
{ "sub": "u_42", "name": "Asha Rao", "email": "asha@shop.example", "email_verified": true, "locale": "en-GB" }| Get claims from | When |
|---|---|
| ID token | At login; the common case |
| UserInfo | Need more or fresher profile data; provider keeps ID tokens small |
| Your own database | Everything after the first login; you own the user record |
98. What are the OIDC Discovery and JWKS endpoints?
The short answer
Discovery is a JSON document at <issuer>/.well-known/openid-configuration that lists everything a client needs: the issuer, the authorize, token, UserInfo and logout endpoint URLs, the supported scopes, response types and signing algorithms, and jwks_uri. JWKS, the JSON Web Key Set at jwks_uri, publishes the provider's current public signing keys, each with a kid. Clients fetch discovery once, cache the keys, and pick the key matching each token's kid, which lets the provider rotate keys without breaking anyone.
json
{
"issuer": "https://auth.shop.example",
"authorization_endpoint": "https://auth.shop.example/authorize",
"token_endpoint": "https://auth.shop.example/token",
"userinfo_endpoint": "https://auth.shop.example/userinfo",
"jwks_uri": "https://auth.shop.example/.well-known/jwks.json",
"end_session_endpoint": "https://auth.shop.example/logout",
"id_token_signing_alg_values_supported": ["RS256", "ES256"],
"code_challenge_methods_supported": ["S256"]
}Verifying tokens against a JWKS, with caching handled for you:
ts
import { createRemoteJWKSet, jwtVerify } from 'jose'
const jwks = createRemoteJWKSet(new URL('https://auth.shop.example/.well-known/jwks.json')) // (1)
export async function verifyIdToken(idToken: string, nonce: string) {
const { payload } = await jwtVerify(idToken, jwks, { // (2)
issuer: 'https://auth.shop.example',
audience: config.CLIENT_ID,
algorithms: ['RS256', 'ES256'],
})
if (payload.nonce !== nonce) throw new Error('Nonce mismatch') // (3)
return payload
}- A key set that fetches and caches the provider's keys. When a token arrives with an unknown
kid, it refetches, which is how key rotation just works. - Signature, issuer, audience, expiry and algorithm are all checked here.
- The nonce check is specific to ID tokens, so do it yourself.
99. How does an OIDC login flow work end to end?
The short answer
It is the authorization code flow with PKCE, plus three OIDC pieces: the openid scope, a nonce, and the ID token. Your app redirects the user to the provider with scope=openid email profile, a state, a nonce and the PKCE challenge. The user signs in there, and the provider redirects back with a code. Your server checks state, exchanges the code and verifier for an ID token and an access token, and verifies the ID token, including aud and nonce. Finally it finds or creates the local user by iss and sub, and starts its own session.
state and nonce look similar but protect different things:
state | nonce | |
|---|---|---|
| Sent in | Authorize request | Authorize request |
| Comes back in | The callback URL | The ID token, signed |
| Stops | Forged callbacks, login CSRF | A replayed or substituted ID token |
100. What are front-channel and back-channel logout in OIDC?
The short answer
Both let the OpenID provider tell every app a user signed in to that the user has logged out. In front-channel logout, the provider's logout page loads each app's logout URL in a hidden iframe in the user's browser, so each app can clear its session cookie. It is simple but unreliable, because browsers increasingly block third-party cookies in iframes and the user may close the tab. In back-channel logout, the provider sends a signed logout token directly to each app's server, which then deletes that user's sessions. Back-channel is more reliable and is preferred.
Handling a back-channel logout token:
- Verify it like an ID token: signature,
iss,audis your client ID,iatrecent. - Check it has the logout
eventsclaim, and nononce, so an ID token cannot be passed off as a logout token. - Find sessions by
sid, the provider's session ID you saved at login, or bysubfor all of that user's sessions. - Delete them, and respond
200.
This only works if your sessions are stored server-side, so you can delete one by ID. Another reason stateful sessions are common for browser apps.
101. How do you implement OAuth-based login in a web application?
The short answer
Use a certified OIDC client library rather than writing the protocol yourself. Register your app with the provider to get a client_id, a secret, and an exact redirect URI. On "Sign in", generate state, nonce and a PKCE verifier, store them in a short-lived server session, and redirect to the provider. On the callback, let the library check state, exchange the code, and verify the ID token. Then find or create the user by iss and sub, regenerate your session ID, store the user ID, and keep any provider tokens on the server.
ts
import * as oidc from 'openid-client'
const provider = await oidc.discovery(new URL('https://accounts.google.com'), config.CLIENT_ID, config.CLIENT_SECRET) // (1)
app.get('/auth/google', async (req, res) => {
const verifier = oidc.randomPKCECodeVerifier()
const state = oidc.randomState()
const nonce = oidc.randomNonce()
req.session.oidc = { verifier, state, nonce } // (2)
const url = oidc.buildAuthorizationUrl(provider, {
redirect_uri: config.REDIRECT_URI,
scope: 'openid email profile',
code_challenge: await oidc.calculatePKCECodeChallenge(verifier),
code_challenge_method: 'S256',
state, nonce,
})
res.redirect(url.href)
})
app.get('/auth/google/callback', async (req, res, next) => {
const saved = req.session.oidc
if (!saved) return next(new HttpError(400, 'No login in progress'))
delete req.session.oidc
const currentUrl = new URL(req.originalUrl, config.PUBLIC_URL)
const tokens = await oidc.authorizationCodeGrant(provider, currentUrl, { // (3)
pkceCodeVerifier: saved.verifier, expectedState: saved.state, expectedNonce: saved.nonce, idTokenExpected: true,
})
const claims = tokens.claims()! // (4)
const user = await users.findOrCreateByIdentity({
issuer: claims.iss, subject: claims.sub, // (5)
email: claims.email_verified ? String(claims.email) : undefined,
})
req.session.regenerate((err) => { // (6)
if (err) return next(err)
req.session.userId = user.id
res.redirect('/')
})
})- Discovery loads every endpoint and the signing keys from the provider's well-known URL.
- Remember the three random values for this one login attempt.
- The library checks
state, exchanges the code with the verifier, and verifies the ID token, including its signature,iss,aud,expandnonce. - The verified ID token claims.
- Link by issuer and subject, never by email alone. Use the email only if the provider says it is verified (the account takeover trap).
- A fresh session ID, then your normal cookie session from here on.
Production checklist:
| Item | Why |
|---|---|
| Exact redirect URI registered, no wildcards | Stops codes being sent to an attacker's URL |
| HTTPS everywhere | Codes and cookies travel safely |
| Short-lived login state in the session | A stale or missing state means reject |
Handle error=access_denied in the callback | The user clicked "Cancel" |
| Store provider refresh tokens encrypted, if kept | They are long-lived credentials |
| Account linking rules | Same person, several providers |