Skip to content

Interview PrepOAuth & OIDC · Advanced

OAuth 2.0 Flows ​

81. What is the Authorization Code flow? ​

The short answer

It is the main OAuth flow for apps acting for a user. The client redirects the browser to the authorization server's /authorize endpoint. The user logs in and consents there. The server redirects back to the client's registered redirect_uri with a short-lived, single-use authorization code. The client then sends that code directly to the /token endpoint, with its own authentication or PKCE verifier, and receives the tokens. Tokens never pass through the browser's address bar, which is why this flow replaced the older implicit flow.

Why a code first, and not the token straight away? The redirect back to your app travels through the browser, and URLs leak: into history, logs, Referer headers and browser extensions. A code is useless on its own. It expires in about a minute, works once, and can only be exchanged by the client that started the flow. The real tokens come over a direct, back-channel HTTPS call the browser never sees.

82. How does the Authorization Code flow with PKCE work end to end? ​

The short answer

The client creates a random code verifier and its SHA-256 hash, the code challenge. It sends the user to /authorize with client_id, redirect_uri, scope, a random state and the code_challenge. The user logs in and consents. The server redirects back with code and state. The client checks state, then posts the code and the original code_verifier to /token. The server hashes the verifier, compares it with the stored challenge, and only then returns the access token, refresh token, and with OIDC an ID token.

browseryour appauth server① verifier = randomchallenge = sha256(it)③ login, consentstore challengeredirect② /authorize + state + challenge④ /callback?code=…&state=…callback⑤ code + verifier⑥ tokens
Only the app that started the flow can finish it. ① The app keeps the verifier secret and sends out only its hash. ② and ③ The server remembers the hash with the code it issues. ④ The code comes back through the browser, where it could be intercepted. ⑤ To use it, the app must show the original verifier. ⑥ The server checks that the verifier hashes to the stored challenge, then hands over tokens.
ts
import { randomBytes, createHash } from 'node:crypto'

app.get('/auth/login', (req, res) => {
  const verifier = randomBytes(32).toString('base64url')                         // (1)
  const challenge = createHash('sha256').update(verifier).digest('base64url')   // (2)
  const state = randomBytes(16).toString('base64url')
  req.session.oauth = { verifier, state }                                        // (3)
  const url = new URL('https://auth.shop.example/authorize')
  url.search = new URLSearchParams({
    response_type: 'code', client_id: config.CLIENT_ID, redirect_uri: config.REDIRECT_URI,
    scope: 'openid profile email orders:read', state, code_challenge: challenge, code_challenge_method: 'S256',
  }).toString()
  res.redirect(url.toString())                                                   // (4)
})

app.get('/auth/callback', async (req, res) => {
  const saved = req.session.oauth
  if (!saved || req.query.state !== saved.state) throw new HttpError(400, 'Bad state')   // (5)
  delete req.session.oauth
  const tokenRes = await fetch('https://auth.shop.example/token', {
    method: 'POST',
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    body: new URLSearchParams({
      grant_type: 'authorization_code', code: String(req.query.code), redirect_uri: config.REDIRECT_URI,
      client_id: config.CLIENT_ID, client_secret: config.CLIENT_SECRET, code_verifier: saved.verifier,   // (6)
    }),
  })
  if (!tokenRes.ok) throw new HttpError(401, 'Login failed')
  const tokens = await tokenRes.json()
  const claims = await verifyIdToken(tokens.id_token)                            // (7)
  req.session.regenerate(() => { req.session.userId = claims.sub; res.redirect('/') })   // (8)
})
  1. 32 random bytes for the verifier, the secret half.
  2. Its SHA-256 hash, Base64url-encoded, is the challenge, the public half.
  3. Keep the verifier and state on the server, in the session, until the callback.
  4. Send the user to the authorization server. Only the challenge leaves your server.
  5. Check state, which proves this callback belongs to a login this browser started.
  6. Exchange the code, proving possession with the verifier. A confidential client also sends its secret.
  7. Verify the ID token before trusting who logged in (the ID token question).
  8. Start your own session with a fresh session ID.

Check this with the official example. RFC 7636 gives the verifier dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk, whose S256 challenge is E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM. Line (2) produces exactly that.

83. What are a PKCE code verifier and code challenge? ​

The short answer

PKCE, Proof Key for Code Exchange and pronounced "pixy", uses a pair of values. The code verifier is a high-entropy random string, 43 to 128 characters, that the client creates for each login and keeps secret. The code challenge is derived from it, BASE64URL(SHA256(verifier)) with method S256, and is sent in the /authorize request. Later, the client sends the verifier to /token. The server hashes it and checks that it matches the challenge it saw earlier. A hash cannot be reversed, so seeing the challenge does not reveal the verifier.

Code verifierCode challenge
CreatedRandomly, per loginBASE64URL(SHA256(verifier))
SentOnly to /token, server to serverIn the /authorize URL, through the browser
Secret?YesNo, safe to expose
Length43 to 128 characters from A-Z a-z 0-9 - . _ ~43 characters for S256

Never use the plain method. It sends the verifier itself as the challenge, so anyone who sees the authorize URL can complete the exchange. It exists only for clients that cannot compute SHA-256, which today means none.

84. How does PKCE improve security, and which attacks does it mitigate? ​

The short answer

PKCE ties the authorization code to the client instance that started the login. Anyone who steals the code, from a malicious app registered for the same custom URL scheme on a phone, a browser extension, logs or a leaky redirect, cannot exchange it, because they do not have the verifier. That stops authorization code interception and authorization code injection, where an attacker pushes a stolen code into the victim's session. It also gives some CSRF protection for the callback. Current OAuth guidance requires PKCE for every client, not just public ones.

The original attack on mobile, step by step:

  1. A banking app registers bankapp://callback as its redirect URI.
  2. A malicious app on the same phone registers the same scheme. The operating system may deliver the redirect to either one.
  3. The user logs in at the bank. The redirect with the code goes to the malicious app.
  4. Without PKCE, the malicious app exchanges the code for tokens. The bank app was public, so there was no secret to stop it.
  5. With PKCE, the exchange fails: the verifier stayed inside the real bank app.
AttackStopped by PKCE?
Stolen code exchanged by an attackerYes
Stolen code injected into the victim's sessionYes, the verifier will not match
Forged callback, login CSRFMostly; still send and check state
Stolen access token after the exchangeNo: use short tokens, sender binding with DPoP
Phishing the user's passwordNo: use passkeys

85. What is the Client Credentials flow, and when is it appropriate? ​

The short answer

In the client credentials flow, a service gets an access token for itself, with no user involved. It sends its client_id and its secret, or better a signed JWT or mTLS certificate, to the /token endpoint with grant_type=client_credentials, and receives a short-lived access token with the scopes that client is allowed. It is right for machine-to-machine calls: a nightly billing job calling the invoices API, or one microservice calling another. It is wrong whenever the action should be tied to a specific user's permissions.

ts
async function getServiceToken() {
  const res = await fetch('https://auth.shop.example/token', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
      Authorization: 'Basic ' + Buffer.from(`${config.CLIENT_ID}:${config.CLIENT_SECRET}`).toString('base64'),   // (1)
    },
    body: new URLSearchParams({ grant_type: 'client_credentials', scope: 'invoices:write' }),   // (2)
  })
  const { access_token, expires_in } = await res.json()
  return { token: access_token, expiresAt: Date.now() + (expires_in - 30) * 1000 }   // (3)
}
  1. The service authenticates as itself. Here with a secret in HTTP Basic. In production prefer private_key_jwt or mTLS, so no shared secret exists.
  2. Ask only for the scopes this job needs.
  3. Cache the token until shortly before it expires, instead of fetching a new one for every call.

No refresh token is issued, because the service can simply ask again with its credentials.

86. What is the Device Authorization flow? ​

The short answer

The device flow, RFC 8628, lets a device with no browser or keyboard, such as a smart TV, a game console or a command-line tool, get tokens for a user. The device asks the authorization server for a device code and a short user code. It shows "go to example.com/activate and enter WDJB-MJHT". The user does that on their phone, logs in and approves. Meanwhile the device polls the token endpoint with its device code, and once the user approves, receives tokens. GitHub's CLI and many TV apps use it.

smart TV② go toshop.example/tvWDJB-MJHTuser's phone③ sign in, enter codeauth serverdevice code ↔ user codepending, then approved① request device code④ poll every 5 s: still pending?⑤ approved: tokens
Log in on the device that has a keyboard. ① and ② The TV gets a code pair and shows the short one. ③ The user approves on their phone. ④ The TV keeps asking. ⑤ After approval, the next poll returns tokens. The user never types a password on the TV.

Risk to mention. Attackers have used this flow for phishing: they start a device login themselves and send the victim a real Microsoft or Google link with "enter this code to continue". The victim approves the attacker's device. Organisations that do not need the device flow should block it, and the approval screen should say clearly which device is being authorised.

87. What was the Implicit flow, and why is it no longer recommended? ​

The short answer

The implicit flow was designed for browser apps in 2012, when browsers could not make cross-origin calls to a token endpoint. The authorization server put the access token directly in the redirect URL fragment, #access_token=…, with no code and no exchange. That exposes the token in the browser's history and to any script, gives no way to bind it to the client, and cannot be protected by PKCE. RFC 9700, the OAuth security best practice, says not to use it. Browser apps now use the authorization code flow with PKCE.

ImplicitAuthorization code + PKCE
Token deliveredIn the URL fragmentBy a back-channel POST
Token in browser historyPossibleNo
Proof the receiver started the flowNoneThe PKCE verifier
Refresh tokensNot allowedAllowed, with rotation
StatusDeprecated by RFC 9700Recommended

Why it existed. In 2012 most browsers had no CORS, so a page could not call auth.example/token. Once CORS was universal, the reason disappeared, and its weaknesses remained.

88. What was the Resource Owner Password Credentials flow, and why is it no longer recommended? ​

The short answer

In the password grant, the user types their username and password into the client app, and the client sends them to the token endpoint to get tokens. It defeats the purpose of OAuth: the client sees the password, users learn to type passwords into third-party apps, which is what phishing relies on, and it cannot support MFA, passkeys or federated login, because the identity provider never shows its own login page. RFC 9700 says it must not be used, and OAuth 2.1 removes it entirely.

What to use instead:

Old reason for the password grantUse now
"Our own first-party mobile app"Authorization code with PKCE in the system browser
"A script needs a token"Client credentials
"The device has no browser"Device authorization flow (question 86)
"Migrating legacy users"A one-time migration at the IdP's login page

89. How does the OAuth token refresh flow work? ​

The short answer

When the access token expires, or shortly before, the client sends grant_type=refresh_token with the refresh token, and its client authentication if it is confidential, to the /token endpoint. The authorization server checks that the refresh token is valid, unrevoked and issued to this client, then returns a new access token and, with rotation, a new refresh token that replaces the old one. The client can ask for the same or fewer scopes, never more. If the refresh fails, the client must send the user through login again.

http
POST /token HTTP/1.1
Host: auth.shop.example
Content-Type: application/x-www-form-urlencoded

grant_type=refresh_token&refresh_token=8xLOxBtZp8&client_id=web-app&scope=orders:read

Avoid refresh storms in a single-page app. If ten API calls get 401 at once, they must not all refresh in parallel, because with rotation nine of them would look like token reuse. Share one refresh promise:

ts
let refreshing: Promise<string> | null = null

export function getFreshAccessToken() {
  refreshing ??= refreshTokens().finally(() => { refreshing = null })            // (1)
  return refreshing
}
  1. The first caller starts the refresh; everyone else awaits the same promise. When it settles, the slot is cleared for next time.

90. How does OAuth logout work, and what limitations should be considered? ​

The short answer

OAuth itself has no logout. "Logging out" really means several separate things: ending your app's session; revoking the refresh token, and the access token if possible, at the authorization server's revocation endpoint, RFC 7009; and, if you want, ending the user's session at the identity provider with OpenID Connect's RP-initiated logout. The limits: already-issued JWT access tokens stay valid until they expire, other apps using the same identity provider session stay logged in unless you use front-channel or back-channel logout, and every step can fail independently.

A logout handler that does the full job:

ts
app.post('/logout', async (req, res) => {
  const { refreshToken, idToken } = req.session.tokens ?? {}
  if (refreshToken) {
    await fetch('https://auth.shop.example/revoke', {                            // (1)
      method: 'POST',
      headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
      body: new URLSearchParams({ token: refreshToken, token_type_hint: 'refresh_token', client_id: config.CLIENT_ID, client_secret: config.CLIENT_SECRET }),
    }).catch(() => {})                                                           // (2)
  }
  req.session.destroy(() => {                                                    // (3)
    const url = new URL('https://auth.shop.example/logout')
    url.search = new URLSearchParams({ id_token_hint: idToken ?? '', post_logout_redirect_uri: `${config.PUBLIC_URL}/` }).toString()
    res.redirect(url.toString())                                                 // (4)
  })
})
  1. Revoke the refresh token, so it cannot make new access tokens.
  2. Do not let a failed revocation block logout. Log it and continue.
  3. End your own session.
  4. Optionally end the IdP session too, so the next login asks for credentials again. Skip this step if users expect to stay signed in to their other apps.
What logs outCovered by
Your appDestroying your session
Future tokens for your appRevoking the refresh token
The identity provider sessionRP-initiated logout
Other apps using the same IdPFront-channel or back-channel logout (the OIDC logout question)
Access tokens already issuedOnly expiry, a deny list or introspection

91. What is dynamic client registration? ​

The short answer

Dynamic client registration, RFC 7591, lets a client register itself with an authorization server through an API, instead of an admin creating it by hand in a console. The client posts its metadata, such as redirect URIs, name, grant types and public keys, to a registration endpoint, and receives a client_id, and possibly a secret. It suits platforms with many clients created automatically: SaaS integrations, developer platforms, and AI agents connecting to tool servers. Because anyone could register, servers usually require an initial access token or apply strict policies to what self-registered clients may do.

http
POST /register HTTP/1.1
Host: auth.shop.example
Authorization: Bearer <initial access token>
Content-Type: application/json

{ "client_name": "Acme Reports", "redirect_uris": ["https://reports.acme.example/callback"],
  "grant_types": ["authorization_code", "refresh_token"], "token_endpoint_auth_method": "private_key_jwt" }

The response contains the new client_id, and a registration access token for updating or deleting the registration later.

Risks to control: attackers registering look-alike apps for consent phishing (the consent screen question), redirect URIs on domains the registrant does not own, and unlimited registrations. Require verification and admin approval before a self-registered client may request sensitive scopes.

92. What is token exchange, and when can it be useful? ​

The short answer

Token exchange, RFC 8693, lets a service trade one token for another at the authorization server, with grant_type=urn:ietf:params:oauth:grant-type:token-exchange. The common use is in microservices: the orders service receives the user's token, and exchanges it for a new token meant only for the payments API, with fewer scopes and a short life, still identifying the user. That avoids forwarding a powerful token everywhere. It also supports delegation, where the new token records both the user and the service acting for them, and swapping tokens between trust domains.

http
POST /token HTTP/1.1
Host: auth.shop.example
Authorization: Basic b3JkZXJzOnMzY3IzdA==
Content-Type: application/x-www-form-urlencoded

grant_type=urn:ietf:params:oauth:grant-type:token-exchange
&subject_token=eyJhbGci…user-token
&subject_token_type=urn:ietf:params:oauth:token-type:access_token
&audience=payments-api
&scope=payments:charge

Reading the request: the orders service authenticates as itself, hands over the user's token as the subject_token, and asks for a token whose aud is the payments API, limited to payments:charge. The response token says "user u_42, acting through the orders service, may charge a payment". If the payments service is compromised, that token is useless against any other API (securing microservices).

Without exchangeWith exchange
The user's broad token is forwarded to every serviceEach hop gets a narrow token for one audience
Every service can call every other API as the userOnly the intended API accepts each token
No record of which service actedact claim records the acting service

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