Skip to content

Interview PrepOAuth & OIDC · Core

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:

PieceWhat it gives you
openid scopeTurns an OAuth request into an OIDC login
ID tokenA standard, verifiable statement of who logged in
Standard claimssub, email, email_verified, name, picture and more
UserInfo endpointFetch profile claims with the access token
DiscoveryOne URL describes every endpoint and setting of the provider
JWKSPublished signing keys, rotated by kid
Logout specsRP-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.0OpenID Connect
PurposeDelegated access to APIsLogging the user in
Main outputAccess tokenID token, plus an access token
Token audienceThe APIYour app, the client
FormatNot specifiedID token is always a JWT
User infoNot specifiedStandard claims and UserInfo endpoint
ScopesDefined by each APIopenid, 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:

  1. Signature, with the provider's key from its JWKS, using only the algorithms you expect.
  2. iss equals the provider you started the login with.
  3. aud contains your own client_id. A token issued to another app must be rejected.
  4. exp is in the future.
  5. nonce equals the value you stored in the session for this login.
  6. auth_time is recent enough, if you asked for a fresh login with max_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 tokenAccess token
Audience, audYour clientThe resource server, the API
Read byYour appThe API
FormatAlways a JWTJWT or opaque
ProvesWho logged in, when, howWhat the holder may do
Sent to APIsNeverYes, as Bearer
LifetimeUsed once at loginMinutes, 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 fromWhen
ID tokenAt login; the common case
UserInfoNeed more or fresher profile data; provider keeps ID tokens small
Your own databaseEverything 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
}
  1. 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.
  2. Signature, issuer, audience, expiry and algorithm are all checked here.
  3. 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.

browseryour serverOpenID provider② sign inMFA or passkey⑤ verify ID token① scope=openid · state · nonce · PKCE③ code + statecallback④ code + verifierID token + access token⑥ your session
OAuth's code flow with an identity receipt. The redirects in ① and ③ carry only a request and a code. The tokens arrive server to server in ④. Step ⑤ is what makes this a login: checking the ID token's signature, issuer, audience, expiry and nonce. Step ⑥ links the provider's user to your own.

state and nonce look similar but protect different things:

statenonce
Sent inAuthorize requestAuthorize request
Comes back inThe callback URLThe ID token, signed
StopsForged callbacks, login CSRFA 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.

front-channel, through the browserprovider's logout page in the browserhidden iframesapp A /logoutapp B /logoutblocked cookies break itback-channel, server to serverprovider's serversigned logout token: sub, sidapp A serverdelete sessionsapp B serverdelete sessionsdirect POST
Who carries the message. Front-channel relies on the user's browser to visit each app, which modern privacy protections often prevent. Back-channel has the provider call each app's server directly, so it works even after the tab is closed.

Handling a back-channel logout token:

  1. Verify it like an ID token: signature, iss, aud is your client ID, iat recent.
  2. Check it has the logout events claim, and no nonce, so an ID token cannot be passed off as a logout token.
  3. Find sessions by sid, the provider's session ID you saved at login, or by sub for all of that user's sessions.
  4. 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('/')
  })
})
  1. Discovery loads every endpoint and the signing keys from the provider's well-known URL.
  2. Remember the three random values for this one login attempt.
  3. The library checks state, exchanges the code with the verifier, and verifies the ID token, including its signature, iss, aud, exp and nonce.
  4. The verified ID token claims.
  5. Link by issuer and subject, never by email alone. Use the email only if the provider says it is verified (the account takeover trap).
  6. A fresh session ID, then your normal cookie session from here on.

Production checklist:

ItemWhy
Exact redirect URI registered, no wildcardsStops codes being sent to an attacker's URL
HTTPS everywhereCodes and cookies travel safely
Short-lived login state in the sessionA stale or missing state means reject
Handle error=access_denied in the callbackThe user clicked "Cancel"
Store provider refresh tokens encrypted, if keptThey are long-lived credentials
Account linking rulesSame person, several providers

Combine chapters into one PDF

Pick the chapters you want. They print in the order you pick them.

Interview Prep
Authentication & Identity
Cookies & sessions
Authentication
Tokens
OAuth & OIDC
Enterprise SSO
Directories
Authorization
Other topics
Nothing picked yet