OAuth vulnerabilities: how "Sign in with" goes wrong, and the callback checks that refuse each attack
When a customer clicks "Sign in with" a provider, your application runs the OAuth 2.0 authorisation code flow, and OpenID Connect tells it who signed in.
This guide explains each step in plain English, what state, PKCE, the nonce and an exactly registered redirect URI each protect, the attacks that work when one is missing, and a lab with a mock provider and callback tests you run on your own machine with Node.js alone.
In this guide
Authorisation code flow sequence and callback test lab
An illustration with invented users. Part 1 sets out the authorisation code flow with PKCE and OpenID Connect as nine numbered steps between the browser, your application and the provider's two endpoints, with the value that protects each step and the specification section behind it.
How to use itHide the instructions
Parts 2 to 5 are a Node.js lab with no installs: a mock provider, an application with a "Sign in with" button in a flawed and a fixed version, thirteen callback scenarios printed request by request, and a regression test that fails on the flawed version. Run it on your own machine, for learning and for testing code you own or are authorised to test.
oauth-oidc-security.txt
Introduction5 lines
Part 1: The authorisation code flow, step by step101 lines
Part 2: The lab files1,002 lines
Part 3: Every scenario against both versions403 lines
Part 4: The regression test77 lines
Part 5: Point the tests at your own application5 lines
Whole template1,623 lines
ILLUSTRATION ONLY. The provider, the application, the users Alice, Bob and Mallory, their addresses and every request below are invented for this page. The lab runs on your own machine, binds to 127.0.0.1 on ports the system picks, keeps everything in memory and signs nobody in to anything real. Use it for learning and for testing code you own or are authorised in writing to test.
What this asset is, and what it is not. Part 1 is the authorisation code flow with PKCE and OpenID Connect as nine numbered steps, each with the value that protects it and the specification section behind that value. Parts 2 to 5 are a lab: a mock provider, an application with a "Sign in with" button in a flawed and a fixed version, thirteen scenarios that print every request in order, and a regression test. A mock provider proves what your callback code does with a provider's answers. It proves nothing about what a real provider does.
Written and run on: Node.js v26.0.0, the only version it was run on. It uses node:http, node:crypto, node:test, node:assert and the fetch function built into Node.js, so there is nothing to install. Every output below comes from that run; timings will differ on your machine.
================================================================
PART 1: THE AUTHORISATION CODE FLOW, STEP BY STEP
================================================================
Who is involved
Browser the person's web browser
Your application the OAuth client; OpenID Connect calls it the relying party
Authorisation endpoint the provider's page where the person signs in and agrees
Token endpoint the provider's address that swaps a code for tokens; in this
flow your application's server calls it, not the browser
Source names used below
RFC 6749 The OAuth 2.0 Authorization Framework (IETF, October 2012)
RFC 7636 Proof Key for Code Exchange by OAuth Public Clients (IETF, September 2015)
RFC 9700 Best Current Practice for OAuth 2.0 Security (IETF, BCP 240, January 2025)
RFC 9207 OAuth 2.0 Authorization Server Issuer Identification (IETF, March 2022)
OIDC Core OpenID Connect Core 1.0 incorporating errata set 2 (OpenID Foundation, 15 December 2023)
ASVS 5.0 OWASP ASVS 5.0.0, chapter V10 OAuth and OIDC
The requirement words (MUST, MUST NOT, SHOULD, MAY, REQUIRED, RECOMMENDED, OPTIONAL) are each source's own, and the party a rule falls on is named wherever the source names it.
STEP 1 BROWSER TO YOUR APPLICATION
Request: GET /login, when the person clicks "Sign in with" the provider.
Your application creates a sign-in attempt, keeps it on its server and ties it to this browser with an HttpOnly cookie:
state a fresh random value
nonce a fresh random value
code_verifier a fresh random value of 43 to 128 characters; 32 random bytes, base64url-encoded, is RECOMMENDED (RFC 7636 4.1)
code_challenge BASE64URL(SHA256(code_verifier)), the S256 method (RFC 7636 4.2)
Rules: the PKCE challenge or OpenID Connect nonce MUST be transaction-specific and securely bound to the client and the user agent in which the transaction was started (RFC 9700 2.1.1). ASVS 5.0 requirement 10.1.2 asks for the code_verifier, state or nonce to be not guessable, specific to the transaction and securely bound to the client and the browser session.
STEP 2 YOUR APPLICATION TO BROWSER
Response: a 302 redirect to the authorisation endpoint carrying
response_type=code, client_id, redirect_uri, scope, state, nonce, code_challenge, code_challenge_method=S256
What protects it:
redirect_uri the exact value registered at the provider; REQUIRED in OpenID Connect (OIDC Core 3.1.2.1)
scope MUST contain openid for an OpenID Connect request (OIDC Core 3.1.2.1); request only the scopes the feature needs (ASVS 5.0 10.2.3)
state RECOMMENDED (RFC 6749 4.1.1; OIDC Core 3.1.2.1)
nonce OPTIONAL in the code flow, with sufficient entropy when used (OIDC Core 3.1.2.1); the lab always sends one
code_challenge sent by the client with its method (RFC 7636 4.3); a client capable of S256 MUST use it (RFC 7636 4.2); public clients MUST use PKCE and it is RECOMMENDED for confidential clients (RFC 9700 2.1.1)
STEP 3 BROWSER TO AUTHORISATION ENDPOINT
Request: GET /authorise with the parameters from step 2.
The provider:
compares redirect_uri with the registered values; the authorisation server MUST use exact string matching, except for port numbers in localhost redirect URIs of native apps (RFC 9700 2.1 and 4.1.3; ASVS 5.0 10.4.1)
on a missing, invalid or mismatching redirect URI, SHOULD inform the person and MUST NOT automatically redirect to it (RFC 6749 4.1.2.1)
authenticates the person and establishes whether they grant the request (RFC 6749 4.1, step B)
MUST associate the code_challenge and its method with the code it issues (RFC 7636 4.4)
MUST include the nonce, when one was sent, in the ID Token (OIDC Core 2)
STEP 4 AUTHORISATION ENDPOINT TO BROWSER
Response: a 302 redirect to redirect_uri with code and state added.
What protects it:
code MUST expire shortly after it is issued, with a maximum lifetime of 10 minutes RECOMMENDED, and is bound to the client identifier and redirection URI (RFC 6749 4.1.2)
state REQUIRED in the response when the request carried it, as the exact value received (RFC 6749 4.1.2)
This is where the code passes through the browser, and RFC 9700 4.2 and 4.3 describe it leaking through Referer headers and browser history.
STEP 5 BROWSER TO YOUR APPLICATION: THE CALLBACK
Request: GET /callback with code and state.
Your application:
finds the sign-in attempt named by this browser's cookie and deletes it, so the attempt is used once
refuses the request if state is missing or does not match the stored value
Rules: the client MUST implement CSRF protection for its redirection URI, and SHOULD use state to carry a binding value that MUST contain a non-guessable value (RFC 6749 10.12). Clients MUST prevent CSRF: a client that has ensured the provider supports PKCE MAY rely on PKCE for it, in OpenID Connect flows the nonce provides it, and otherwise one-time-use state values securely bound to the user agent MUST be used (RFC 9700 2.1). The client MUST validate the response according to RFC 6749, especially sections 4.1.2 and 10.12 (OIDC Core 3.1.2.7).
Lab scenarios: S2, S3 and S10.
STEP 6 YOUR APPLICATION TO TOKEN ENDPOINT, SERVER TO SERVER
Request: POST /token with grant_type=authorization_code, code, redirect_uri and code_verifier, authenticated with your client credential.
What protects it:
redirect_uri REQUIRED when the authorisation request carried it, and the values MUST be identical (RFC 6749 4.1.3)
code_verifier REQUIRED (RFC 7636 4.5)
client credential a confidential client MUST authenticate (RFC 6749 4.1.3); the lab uses HTTP Basic, which RFC 6749 2.3.1 allows
STEP 7 TOKEN ENDPOINT CHECKS, THEN ANSWERS
The authorisation server MUST require client authentication from a confidential client, ensure the code was issued to this client, verify that the code is valid, and, when the authorisation request carried redirect_uri, ensure it is present and identical (RFC 6749 4.1.3).
It MUST deny a code used more than once, and SHOULD revoke, when possible, all tokens already issued from it (RFC 6749 4.1.2).
It computes the challenge from code_verifier and MUST return invalid_grant when it does not equal the stored code_challenge (RFC 7636 4.6). When a valid code_challenge was sent, it MUST enforce the correct use of code_verifier, and it MUST reject a code_verifier sent for a code issued without a code_challenge (RFC 9700 2.1.1 and 4.8.2).
Response: an access token and, in OpenID Connect, an ID Token.
Lab scenarios: S7, and checks P1 to P5 on the mock provider.
STEP 8 YOUR APPLICATION VALIDATES THE ID TOKEN
The client MUST validate the ID Token (OIDC Core 3.1.3.7):
iss MUST exactly match the provider's issuer identifier
aud MUST contain your client_id; the token MUST be rejected if it lists audiences you do not trust
exp the current time MUST be before it
nonce when one was sent, a nonce claim MUST be present and equal to the value stored in step 1; the client SHOULD check it for replay
signature ID Tokens MUST be signed (OIDC Core 2); for a token received straight from the token endpoint, TLS server validation MAY be used to validate the issuer in place of checking the signature (OIDC Core 3.1.3.7). The lab checks the signature anyway.
A client relying on the nonce against code injection MUST validate it in the ID Token from the token endpoint, and MUST disregard every token until that check succeeds (RFC 9700 4.5.3.2).
Lab scenarios: S4 and S5.
STEP 9 YOUR APPLICATION DECIDES WHO SIGNED IN
Find the account by iss and sub together, the only claims a relying party can rely on as a stable identifier. Claims such as email, phone_number, preferred_username and name MUST NOT be used as unique identifiers (OIDC Core 5.7; ASVS 5.0 10.5.2).
If the email address matches an existing account, link nothing yet. Read email_verified (OIDC Core 5.1): refuse when it is not true, and otherwise link only after the person signs in to the existing account the way they always have.
Then your application starts its own session.
Lab scenarios: S11, S12 and S13.
IF YOU ACCEPT MORE THAN ONE PROVIDER
A defence against mix-up attacks is REQUIRED. Clients SHOULD use the iss parameter from RFC 9207 or an iss value in the authorisation response, such as the one in the ID Token, and MUST store, with each sign-in attempt and bound to the browser, the issuer the request was sent to (RFC 9700 2.1 and 4.4.2). A client supporting RFC 9207 MUST reject a response whose iss does not match that issuer (RFC 9207 2.4). The lab has one provider and does not test this.
================================================================
PART 2: THE LAB FILES
================================================================
Make an empty folder, save the six files below into it with the names shown, and open a terminal in that folder.
The mock provider has three settings that follow the specifications by default. A scenario switches one off when it needs to show what the application's own check does without the provider's help: S4 turns off includeNonce, S5 turns off enforcePkce and S10 turns off singleUseCodes. The specifications require a provider to do all three, so read those scenarios as defence in depth, not as a description of any provider.
================================================================
FILE 1 OF 6: mock-provider.mjs
================================================================
// mock-provider.mjs: a pretend OpenID provider for the lab. Illustration only.
// It listens on 127.0.0.1, keeps everything in memory, knows four invented
// users and signs ID tokens with an RSA key it makes when it starts. It shows
// what your callback code does with a provider's answers. It proves nothing
// about what any real provider does.
import { createServer } from 'node:http'
import { createHash, generateKeyPairSync, randomBytes, sign, timingSafeEqual } from 'node:crypto'
// Invented users. Picking one with the lab_user parameter stands in for
// signing in at the provider's own sign-in page.
const USERS = {
alice: { sub: 'op-alice-7f3a', email: 'alice@example.com', email_verified: true },
bob: { sub: 'op-bob-21c9', email: 'bob@example.com', email_verified: true },
mallory: { sub: 'op-mallory-9d04', email: 'mallory@example.net', email_verified: true },
// A second provider account Mallory opened with Alice's address, never verified.
'mallory-alias': { sub: 'op-mallory-5e18', email: 'alice@example.com', email_verified: false },
}
const CODE_LIFETIME_SECONDS = 60
const ID_TOKEN_LIFETIME_SECONDS = 300
// settings: the defaults follow the specifications. A scenario switches one
// off to see what the client's own check does without the provider's help.
// enforcePkce check code_verifier against code_challenge (RFC 7636 4.6)
// includeNonce copy the request's nonce into the ID token (OIDC Core 1.0, 2)
// singleUseCodes refuse a code presented a second time (RFC 6749 4.1.2)
export async function startProvider(settings, trace) {
const keys = generateKeyPairSync('rsa', { modulusLength: 2048 })
const provider = {
settings: settings,
trace: trace,
clients: new Map(),
codes: new Map(),
publicKey: keys.publicKey,
privateKey: keys.privateKey,
}
const server = createServer(function (request, response) {
routeProviderRequest(provider, request, response)
})
await listenOnLoopback(server)
provider.server = server
// A real issuer is an https URL (OIDC Core 1.0, section 2). The lab uses
// plain http because it never leaves your machine.
provider.issuer = 'http://127.0.0.1:' + server.address().port
return provider
}
// Registration happens in the provider's console in real life. An entry
// ending in * is a pattern matching anything that starts with the text before
// it, the kind of registration RFC 9700 section 4.1 warns about. Any other
// entry must match exactly.
export function registerClient(provider, client) {
provider.clients.set(client.clientId, client)
}
function routeProviderRequest(provider, request, response) {
const url = new URL(request.url, provider.issuer)
if (request.method === 'GET' && url.pathname === '/authorise') return handleAuthorise(provider, url, response)
if (request.method === 'POST' && url.pathname === '/token') return handleToken(provider, request, response)
sendText(response, 404, 'not-found')
}
// The authorisation endpoint (RFC 6749 4.1.1 and 4.1.2).
function handleAuthorise(provider, url, response) {
const query = url.searchParams
const client = provider.clients.get(query.get('client_id'))
const redirectUri = query.get('redirect_uri') || ''
// A bad client or redirect URI gets an error page instead of a redirect (RFC 6749 4.1.2.1).
if (!client || !isRedirectUriRegistered(client, redirectUri)) {
return sendText(response, 400, 'error page: redirect_uri is not registered for this client')
}
const state = query.get('state')
const user = USERS[query.get('lab_user')]
const scopes = (query.get('scope') || '').split(' ')
if (query.get('response_type') !== 'code' || !user) return redirectWithError(response, redirectUri, 'invalid_request', state)
if (!scopes.includes('openid')) return redirectWithError(response, redirectUri, 'invalid_scope', state)
const challenge = query.get('code_challenge')
// This mock supports only S256, the method RFC 9700 section 2.1.1 says clients should use.
if (challenge && query.get('code_challenge_method') !== 'S256') return redirectWithError(response, redirectUri, 'invalid_request', state)
const code = randomBytes(32).toString('base64url')
provider.codes.set(code, {
clientId: client.clientId,
redirectUri: redirectUri,
user: user,
nonce: query.get('nonce'),
challenge: challenge,
issuedAt: nowInSeconds(),
used: false,
})
const back = new URL(redirectUri)
back.searchParams.set('code', code)
if (state !== null) back.searchParams.set('state', state)
sendRedirect(response, back.toString())
}
function isRedirectUriRegistered(client, redirectUri) {
for (const registered of client.redirectUris) {
const isPattern = registered.endsWith('*')
if (isPattern && redirectUri.startsWith(registered.slice(0, -1))) return true
if (!isPattern && registered === redirectUri) return true
}
return false
}
// The token endpoint (RFC 6749 4.1.3, RFC 7636 4.6).
async function handleToken(provider, request, response) {
const form = new URLSearchParams(await readBody(request))
const client = authenticateClient(provider, request)
if (!client) return sendTokenError(provider, response, form, 401, 'invalid_client', 'client authentication failed')
const grant = provider.codes.get(form.get('code'))
const problem = findGrantProblem(provider, client, grant, form)
if (problem) return sendTokenError(provider, response, form, 400, 'invalid_grant', problem)
logToken(provider, form, '200 access token and ID token issued')
response.writeHead(200, { 'content-type': 'application/json', 'cache-control': 'no-store' })
response.end(JSON.stringify({
access_token: randomBytes(32).toString('base64url'),
token_type: 'Bearer',
expires_in: ID_TOKEN_LIFETIME_SECONDS,
id_token: buildIdToken(provider, client, grant),
}))
}
// The checks run in this order. A code is marked used the first time it is
// presented, so a second presentation fails even if the first one failed.
function findGrantProblem(provider, client, grant, form) {
if (form.get('grant_type') !== 'authorization_code') return 'unsupported grant_type'
if (!grant || grant.clientId !== client.clientId) return 'unknown code'
if (grant.used && provider.settings.singleUseCodes) return 'code already used'
grant.used = true
if (nowInSeconds() - grant.issuedAt > CODE_LIFETIME_SECONDS) return 'code expired'
if (form.get('redirect_uri') !== grant.redirectUri) return 'redirect_uri differs from the authorisation request'
if (!provider.settings.enforcePkce) return ''
return findPkceProblem(grant.challenge, form.get('code_verifier'))
}
// A code issued without a code_challenge is accepted without a verifier, as a
// provider that supports PKCE without requiring it would (RFC 9700 4.8). A
// verifier sent for such a code is refused (RFC 9700 4.8.2).
function findPkceProblem(challenge, verifier) {
if (!challenge) return verifier ? 'code_verifier sent but no code_challenge was' : ''
if (!verifier) return 'code_verifier missing'
const computed = createHash('sha256').update(verifier, 'ascii').digest('base64url')
return computed === challenge ? '' : 'code_verifier does not match code_challenge'
}
// HTTP Basic client authentication (RFC 6749 2.3.1).
function authenticateClient(provider, request) {
const header = readHeader(request, 'Authorization')
if (!header.startsWith('Basic ')) return null
const pair = Buffer.from(header.slice(6), 'base64').toString('utf8')
const colon = pair.indexOf(':')
const client = provider.clients.get(decodeURIComponent(pair.slice(0, colon)))
if (!client) return null
return secretsMatch(client.clientSecret, decodeURIComponent(pair.slice(colon + 1))) ? client : null
}
// An RS256-signed ID token with the claims OIDC Core 1.0 section 2 requires,
// plus the email and email_verified claims from section 5.1.
function buildIdToken(provider, client, grant) {
const now = nowInSeconds()
const claims = {
iss: provider.issuer,
sub: grant.user.sub,
aud: client.clientId,
exp: now + ID_TOKEN_LIFETIME_SECONDS,
iat: now,
email: grant.user.email,
email_verified: grant.user.email_verified,
}
if (grant.nonce !== null && provider.settings.includeNonce) claims.nonce = grant.nonce
const header = { alg: 'RS256', typ: 'JWT', kid: 'lab-key-1' }
const signingInput = encodeJson(header) + '.' + encodeJson(claims)
const signature = sign('sha256', Buffer.from(signingInput), provider.privateKey)
return signingInput + '.' + signature.toString('base64url')
}
function redirectWithError(response, redirectUri, error, state) {
const back = new URL(redirectUri)
back.searchParams.set('error', error)
if (state !== null) back.searchParams.set('state', state)
sendRedirect(response, back.toString())
}
function sendTokenError(provider, response, form, status, error, problem) {
logToken(provider, form, status + ' ' + error + ': ' + problem)
response.writeHead(status, { 'content-type': 'application/json', 'cache-control': 'no-store' })
response.end(JSON.stringify({ error: error, error_description: problem }))
}
// Records each back-channel request by parameter name only, never by value.
function logToken(provider, form, outcome) {
const names = Array.from(form.keys()).join(', ')
provider.trace.push(' back channel: POST provider /token (' + names + ', client credential)')
provider.trace.push(' ' + outcome)
}
// Node.js stores incoming header names in lower case.
function readHeader(request, name) {
return request.headers[name.toLowerCase()] || ''
}
function secretsMatch(expected, received) {
const expectedBytes = Buffer.from(expected)
const receivedBytes = Buffer.from(received)
return expectedBytes.length === receivedBytes.length && timingSafeEqual(expectedBytes, receivedBytes)
}
function encodeJson(value) {
return Buffer.from(JSON.stringify(value)).toString('base64url')
}
function nowInSeconds() {
return Math.floor(Date.now() / 1000)
}
function readBody(request) {
return new Promise(function (resolve) {
const chunks = []
request.on('data', function (chunk) { chunks.push(chunk) })
request.on('end', function () { resolve(Buffer.concat(chunks).toString('utf8')) })
})
}
export function listenOnLoopback(server) {
return new Promise(function (resolve) {
server.listen(0, '127.0.0.1', resolve)
})
}
function sendRedirect(response, location) {
response.writeHead(302, { location: location })
response.end()
}
function sendText(response, status, text) {
response.writeHead(status, { 'content-type': 'text/plain; charset=utf-8' })
response.end(text)
}
================================================================
FILE 2 OF 6: lab-client.mjs
================================================================
// lab-client.mjs: "your application" with a "Sign in with the provider"
// button, in a flawed version and a fixed version. Illustration only.
// Both versions check the ID token's signature, issuer, audience and expiry
// the same way, so every difference in the results comes from the checks
// this lab is about: state, nonce, PKCE, the registered redirect URI, using
// each sign-in attempt once, and account linking.
import { createServer } from 'node:http'
import { createHash, randomBytes, scryptSync, timingSafeEqual, verify } from 'node:crypto'
import { listenOnLoopback, registerClient } from './mock-provider.mjs'
export const CLIENT_ID = 'lab-client'
export const CLIENT_SECRET = 'lab-client-secret-not-for-real-use'
// version is 'flawed' or 'fixed'.
export async function startClient(version, provider) {
const app = {
version: version,
provider: provider,
users: createLocalUsers(),
links: new Map(),
attempts: new Map(),
pendingLinks: new Map(),
sessions: new Map(),
}
const server = createServer(function (request, response) {
routeClientRequest(app, request, response).catch(function () { sendText(response, 500, 'error') })
})
await listenOnLoopback(server)
app.server = server
app.origin = 'http://127.0.0.1:' + server.address().port
app.redirectUri = app.origin + '/callback'
// The configuration difference: the flawed version registered a pattern,
// the fixed version registered the one exact callback URI.
const registered = version === 'fixed' ? app.redirectUri : app.redirectUri + '*'
registerClient(provider, { clientId: CLIENT_ID, clientSecret: CLIENT_SECRET, redirectUris: [registered] })
return app
}
// One local account that existed before sign-in with the provider was added:
// Alice signed up with her email address and a password. Both are invented.
function createLocalUsers() {
const salt = randomBytes(16)
return [{ id: 'local-1', email: 'alice@example.com', emailVerified: true, salt: salt, passwordHash: scryptSync('alice-lab-password', salt, 32) }]
}
async function routeClientRequest(app, request, response) {
const url = new URL(request.url, app.origin)
const isFixed = app.version === 'fixed'
if (request.method === 'GET' && url.pathname === '/login') {
return isFixed ? startSignInFixed(app, response) : startSignInFlawed(app, response)
}
if (request.method === 'GET' && url.pathname === '/callback') {
return isFixed ? finishSignInFixed(app, request, url, response) : finishSignInFlawed(app, url, response)
}
if (request.method === 'POST' && url.pathname === '/link/confirm' && isFixed) return confirmLink(app, request, response)
if (request.method === 'GET' && url.pathname === '/me') return showSession(app, request, response)
sendText(response, 404, 'not-found')
}
// ---------- The flawed version ----------
// Sends the browser to the provider with no state, no nonce and no PKCE.
function startSignInFlawed(app, response) {
sendRedirect(response, buildAuthoriseUrl(app, {}))
}
// Accepts whatever code arrives, and lets the email address decide which
// local account the person gets.
async function finishSignInFlawed(app, url, response) {
const tokens = await redeemCode(app, url.searchParams.get('code'), null)
if (tokens.error) return sendText(response, 400, 'refused: token endpoint said ' + tokens.error)
const claims = verifyIdToken(app, tokens.id_token)
if (!claims) return sendText(response, 400, 'refused: ID token invalid')
const user = findUserByEmail(app, claims.email) || createUser(app, claims.email, claims.email_verified === true)
startSession(app, response, user)
}
// ---------- The fixed version ----------
// Creates a sign-in attempt with its own state, nonce and PKCE verifier,
// kept on the server and tied to this browser by an HttpOnly cookie. Lax,
// not Strict: the provider sends the browser back with a top-level GET from
// another site. Real deployments add Secure; the lab runs on plain http.
function startSignInFixed(app, response) {
const attempt = { id: randomValue(), state: randomValue(), nonce: randomValue(), codeVerifier: randomValue() }
app.attempts.set(attempt.id, attempt)
const codeChallenge = createHash('sha256').update(attempt.codeVerifier, 'ascii').digest('base64url')
response.setHeader('Set-Cookie', 'signin_attempt=' + attempt.id + '; Path=/; HttpOnly; SameSite=Lax')
sendRedirect(response, buildAuthoriseUrl(app, {
state: attempt.state,
nonce: attempt.nonce,
code_challenge: codeChallenge,
code_challenge_method: 'S256',
}))
}
async function finishSignInFixed(app, request, url, response) {
const attempt = takeAttempt(app, request)
if (!attempt) return sendText(response, 400, 'refused: no open sign-in attempt in this browser')
const state = url.searchParams.get('state')
if (!state) return sendText(response, 400, 'refused: state missing')
if (!valuesMatch(attempt.state, state)) return sendText(response, 400, 'refused: state does not match this browser')
const tokens = await redeemCode(app, url.searchParams.get('code'), attempt.codeVerifier)
if (tokens.error) return sendText(response, 400, 'refused: token endpoint said ' + tokens.error)
const claims = verifyIdToken(app, tokens.id_token)
if (!claims) return sendText(response, 400, 'refused: ID token invalid')
if (!claims.nonce) return sendText(response, 400, 'refused: nonce missing from ID token')
if (!valuesMatch(attempt.nonce, claims.nonce)) return sendText(response, 400, 'refused: nonce does not match this sign-in')
resolveAccountFixed(app, claims, response)
}
// Reads the attempt named by this browser's cookie and deletes it, so each
// attempt, and the code that came back for it, is used once.
function takeAttempt(app, request) {
const id = readCookie(request, 'signin_attempt')
const attempt = app.attempts.get(id) || null
app.attempts.delete(id)
return attempt
}
// A provider account is known by iss and sub together, the pair OIDC Core
// 1.0 section 5.7 says a client can rely on. An email address that matches
// an existing account never links on its own: an unverified one is refused,
// and a verified one waits for the person to prove they own that account.
function resolveAccountFixed(app, claims, response) {
const linkKey = claims.iss + ' ' + claims.sub
const linkedUserId = app.links.get(linkKey)
if (linkedUserId) return startSession(app, response, findUserById(app, linkedUserId))
const existing = findUserByEmail(app, claims.email)
if (!existing) {
const user = createUser(app, claims.email, claims.email_verified === true)
app.links.set(linkKey, user.id)
return startSession(app, response, user)
}
if (claims.email_verified !== true) {
return sendText(response, 403, 'refused: the provider has not verified this email, nothing linked')
}
const pendingId = randomValue()
app.pendingLinks.set(pendingId, { linkKey: linkKey, userId: existing.id })
response.setHeader('Set-Cookie', 'pending_link=' + pendingId + '; Path=/; HttpOnly; SameSite=Lax')
sendText(response, 200, 'not signed in: sign in to your existing account to confirm the link')
}
// The person proves they own the existing account by signing in to it the
// way they always have. Only then is the provider account linked.
async function confirmLink(app, request, response) {
const pendingId = readCookie(request, 'pending_link')
const pending = app.pendingLinks.get(pendingId)
const form = new URLSearchParams(await readBody(request))
if (!pending) return sendText(response, 400, 'refused: no link waiting for confirmation')
const user = findUserById(app, pending.userId)
if (!passwordMatches(user, form.get('password') || '')) return sendText(response, 403, 'refused: wrong password, nothing linked')
app.pendingLinks.delete(pendingId)
app.links.set(pending.linkKey, user.id)
startSession(app, response, user)
}
// ---------- Shared by both versions ----------
function buildAuthoriseUrl(app, extra) {
const url = new URL(app.provider.issuer + '/authorise')
url.searchParams.set('response_type', 'code')
url.searchParams.set('client_id', CLIENT_ID)
url.searchParams.set('redirect_uri', app.redirectUri)
url.searchParams.set('scope', 'openid email')
for (const name of Object.keys(extra)) url.searchParams.set(name, extra[name])
return url.toString()
}
// The back-channel call to the token endpoint, authenticated with the client
// secret. The redirect_uri sent here is always the exact registered one.
async function redeemCode(app, code, codeVerifier) {
const form = new URLSearchParams({ grant_type: 'authorization_code', code: code || '', redirect_uri: app.redirectUri })
if (codeVerifier) form.set('code_verifier', codeVerifier)
const credential = Buffer.from(CLIENT_ID + ':' + CLIENT_SECRET).toString('base64')
const response = await fetch(app.provider.issuer + '/token', {
method: 'POST',
headers: { authorization: 'Basic ' + credential, 'content-type': 'application/x-www-form-urlencoded' },
body: form.toString(),
})
return response.json()
}
// Signature, issuer, audience and expiry, as OIDC Core 1.0 section 3.1.3.7
// lists them. A real client uses the keys the issuer provides; the lab hands
// the provider's public key over directly.
function verifyIdToken(app, idToken) {
const parts = String(idToken || '').split('.')
if (parts.length !== 3) return null
const header = decodeJson(parts[0])
if (!header || header.alg !== 'RS256') return null
const signature = Buffer.from(parts[2], 'base64url')
const isSigned = verify('sha256', Buffer.from(parts[0] + '.' + parts[1]), app.provider.publicKey, signature)
const claims = isSigned ? decodeJson(parts[1]) : null
if (!claims || claims.iss !== app.provider.issuer) return null
const audiences = Array.isArray(claims.aud) ? claims.aud : [claims.aud]
if (audiences.length !== 1 || audiences[0] !== CLIENT_ID) return null
if (typeof claims.exp !== 'number' || claims.exp <= Math.floor(Date.now() / 1000)) return null
return claims
}
// A fresh session for the signed-in person. How sessions start, rotate and
// end is session management, with its own guide.
function startSession(app, response, user) {
const sessionId = randomValue()
app.sessions.set(sessionId, user.id)
response.setHeader('Set-Cookie', 'session=' + sessionId + '; Path=/; HttpOnly; SameSite=Lax')
sendText(response, 200, 'signed in as ' + user.email)
}
function showSession(app, request, response) {
const userId = app.sessions.get(readCookie(request, 'session'))
if (!userId) return sendText(response, 401, 'not signed in')
sendText(response, 200, 'signed in as ' + findUserById(app, userId).email)
}
function createUser(app, email, emailVerified) {
const user = { id: 'local-' + (app.users.length + 1), email: email, emailVerified: emailVerified }
app.users.push(user)
return user
}
function findUserByEmail(app, email) {
return app.users.find(function (user) { return user.email === email }) || null
}
function findUserById(app, id) {
return app.users.find(function (user) { return user.id === id }) || null
}
function passwordMatches(user, password) {
if (!user.passwordHash) return false
return timingSafeEqual(user.passwordHash, scryptSync(password, user.salt, 32))
}
// 32 random bytes as base64url: 43 characters, the size RFC 7636 4.1
// recommends for a code verifier, used here for every random value.
function randomValue() {
return randomBytes(32).toString('base64url')
}
function valuesMatch(expected, received) {
const expectedBytes = Buffer.from(String(expected))
const receivedBytes = Buffer.from(String(received))
return expectedBytes.length === receivedBytes.length && timingSafeEqual(expectedBytes, receivedBytes)
}
function decodeJson(part) {
try {
return JSON.parse(Buffer.from(part, 'base64url').toString('utf8'))
} catch {
return null
}
}
function readCookie(request, name) {
const pairs = (request.headers.cookie || '').split('; ')
for (const pair of pairs) {
if (pair.startsWith(name + '=')) return pair.slice(name.length + 1)
}
return ''
}
function readBody(request) {
return new Promise(function (resolve) {
const chunks = []
request.on('data', function (chunk) { chunks.push(chunk) })
request.on('end', function () { resolve(Buffer.concat(chunks).toString('utf8')) })
})
}
function sendRedirect(response, location) {
response.writeHead(302, { location: location })
response.end()
}
function sendText(response, status, text) {
response.writeHead(status, { 'content-type': 'text/plain; charset=utf-8' })
response.end(text)
}
================================================================
FILE 3 OF 6: lab-browser.mjs
================================================================
// lab-browser.mjs: a scripted stand-in for a browser. Each browser keeps its
// own cookies, makes one request at a time without following redirects, and
// writes each request and response to the trace by parameter name, never by
// value. It does not apply SameSite rules or keep history the way a real
// browser does; it only shows what the servers do with each request.
import { request as httpRequest } from 'node:http'
export function createBrowser(name, trace, labels) {
return { name: name, trace: trace, labels: labels, cookies: new Map(), lastLocation: '' }
}
// method is 'GET' or 'POST'. form is an object of fields for a POST.
export async function visit(browser, url, method, form) {
const target = new URL(url)
const headers = {}
const cookieHeader = buildCookieHeader(browser, target.origin)
if (cookieHeader) headers.cookie = cookieHeader
let body = ''
if (method === 'POST') {
headers['content-type'] = 'application/x-www-form-urlencoded'
body = new URLSearchParams(form).toString()
}
const followsRedirect = browser.lastLocation !== '' && target.href.startsWith(browser.lastLocation)
const shownTarget = followsRedirect ? describeFollowedRedirect(browser, target) : describeUrl(browser, target)
browser.trace.push(' browser ' + browser.name + ': ' + (method || 'GET') + ' ' + shownTarget)
const response = await send(target, method || 'GET', headers, body)
storeCookies(browser, target.origin, response.headers['set-cookie'] || [])
const location = response.headers.location || ''
const shown = location ? 'to ' + describeUrl(browser, new URL(location)) : response.text
browser.trace.push(' ' + response.status + ' ' + shown)
browser.lastLocation = location
return { status: response.status, location: location, body: response.text }
}
// node:http never follows a redirect, so each 302 comes back as it was sent.
function send(target, method, headers, body) {
return new Promise(function (resolve, reject) {
const outgoing = httpRequest(target, { method: method, headers: headers }, function (response) {
const chunks = []
response.on('data', function (chunk) { chunks.push(chunk) })
response.on('end', function () {
resolve({ status: response.statusCode, headers: response.headers, text: Buffer.concat(chunks).toString('utf8') })
})
})
outgoing.on('error', reject)
outgoing.end(body)
})
}
// "client /callback ?code, state" or "provider /authorise ?... (signs in at the provider as bob)"
function describeUrl(browser, url) {
const host = browser.labels[url.origin] || url.origin
const names = []
let user = ''
for (const name of url.searchParams.keys()) {
if (name === 'lab_user') user = url.searchParams.get(name)
else names.push(name)
}
let text = host + ' ' + url.pathname
if (names.length) text = text + ' ?' + names.join(', ')
if (user) text = text + ' (signs in at the provider as ' + user + ')'
return text
}
// The request goes to the address in the redirect just above, so only the
// host, path and the lab's sign-in choice are repeated.
function describeFollowedRedirect(browser, url) {
const host = browser.labels[url.origin] || url.origin
const user = url.searchParams.get('lab_user')
const signIn = user ? ', signs in at the provider as ' + user : ''
return host + ' ' + url.pathname + ' (the address above' + signIn + ')'
}
function buildCookieHeader(browser, origin) {
const jar = browser.cookies.get(origin)
if (!jar) return ''
return Array.from(jar.entries()).map(function (entry) { return entry[0] + '=' + entry[1] }).join('; ')
}
function storeCookies(browser, origin, setCookieHeaders) {
for (const setCookie of setCookieHeaders) {
const pair = setCookie.split(';')[0]
const equals = pair.indexOf('=')
if (!browser.cookies.has(origin)) browser.cookies.set(origin, new Map())
browser.cookies.get(origin).set(pair.slice(0, equals), pair.slice(equals + 1))
}
}
================================================================
FILE 4 OF 6: scenarios.mjs
================================================================
// scenarios.mjs: the callback tests, each written once and run against the
// flawed and the fixed client by run-scenarios.mjs and callback.test.mjs.
// Every person, address and account in them is invented.
import { createHash } from 'node:crypto'
import { startProvider } from './mock-provider.mjs'
import { startClient, CLIENT_ID, CLIENT_SECRET } from './lab-client.mjs'
import { createBrowser, visit } from './lab-browser.mjs'
const SPEC_DEFAULTS = { enforcePkce: true, includeNonce: true, singleUseCodes: true }
// A fresh provider and client for every scenario, so no scenario sees
// another one's accounts, codes or sessions.
export async function startLab(version, providerSettings) {
const trace = []
const provider = await startProvider(Object.assign({}, SPEC_DEFAULTS, providerSettings), trace)
const client = await startClient(version, provider)
const labels = {}
labels[provider.issuer] = 'provider'
labels[client.origin] = 'client'
return {
trace: trace,
provider: provider,
client: client,
browser: function (name) { return createBrowser(name, trace, labels) },
close: function () { provider.server.close(); client.server.close() },
}
}
// Clicks "Sign in", signs in at the provider as user, and returns the
// callback URL the provider sent back, without opening it.
async function getCallbackUrl(lab, browser, user) {
const toProvider = await visit(browser, lab.client.origin + '/login')
const back = await visit(browser, toProvider.location + '&lab_user=' + user)
return back.location
}
async function whoIsSignedIn(lab, browser) {
const result = await visit(browser, lab.client.origin + '/me')
return result.body
}
function replaceParameter(url, name, value) {
const changed = new URL(url)
if (value === null) changed.searchParams.delete(name)
else changed.searchParams.set(name, value)
return changed.toString()
}
async function signInAs(lab, browserName, user) {
const browser = lab.browser(browserName)
const result = await visit(browser, await getCallbackUrl(lab, browser, user))
return { status: result.status, response: result.body, afterwards: await whoIsSignedIn(lab, browser) }
}
export const scenarios = [
{
id: 'S1',
title: 'Baseline: Bob signs in for the first time',
run: function (lab) { return signInAs(lab, 'B', 'bob') },
},
{
id: 'S2',
title: 'state missing from the callback',
run: async function (lab) {
const bob = lab.browser('B')
const callback = await getCallbackUrl(lab, bob, 'bob')
lab.trace.push(' (the test removes state from the callback URL)')
const result = await visit(bob, replaceParameter(callback, 'state', null))
return { status: result.status, response: result.body, afterwards: await whoIsSignedIn(lab, bob) }
},
},
{
id: 'S3',
title: 'state from another browser: login CSRF',
run: async function (lab) {
const mallory = lab.browser('M')
const callback = await getCallbackUrl(lab, mallory, 'mallory')
lab.trace.push(' (M stops before the callback and gets V to open it)')
const victim = lab.browser('V')
await visit(victim, lab.client.origin + '/login')
const result = await visit(victim, callback)
return { status: result.status, response: result.body, afterwards: await whoIsSignedIn(lab, victim) }
},
},
{
id: 'S4',
title: 'nonce missing from the ID token',
providerSettings: { includeNonce: false },
run: function (lab) { return signInAs(lab, 'B', 'bob') },
},
{
id: 'S5',
title: "nonce from another sign-in: Bob's code in Mallory's browser, PKCE not enforced",
providerSettings: { enforcePkce: false },
run: injectBobsCode,
},
{
id: 'S6',
title: 'PKCE: the sign-in request carries state, nonce and an S256 code_challenge',
run: async function (lab) {
const result = await visit(lab.browser('B'), lab.client.origin + '/login')
const query = new URL(result.location).searchParams
const names = ['state', 'nonce', 'code_challenge', 'code_challenge_method']
const sent = names.filter(function (name) { return query.has(name) })
return { sent: sent.join(', ') || 'none of them', method: query.get('code_challenge_method') || 'none' }
},
},
{
id: 'S7',
title: "PKCE: Bob's code in Mallory's browser, provider enforcing PKCE",
run: injectBobsCode,
},
{
id: 'S8',
title: 'redirect_uri with a different path',
run: function (lab) { return tryRedirectUri(lab, '/callback/old') },
},
{
id: 'S9',
title: 'redirect_uri with an added query',
run: function (lab) { return tryRedirectUri(lab, '/callback?next=/admin') },
},
{
id: 'S10',
title: 'the same callback URL opened twice',
providerSettings: { singleUseCodes: false },
run: async function (lab) {
const bob = lab.browser('B')
const callback = await getCallbackUrl(lab, bob, 'bob')
const first = await visit(bob, callback)
lab.trace.push(' (the same URL again, as from the browser history)')
const second = await visit(bob, callback)
return { firstVisit: first.status, status: second.status, response: second.body }
},
},
{
id: 'S11',
title: 'account linking: an unverified email matches a local account',
run: function (lab) { return signInAs(lab, 'M', 'mallory-alias') },
},
{
id: 'S12',
title: 'account linking: a verified email matches a local account',
run: function (lab) { return signInAs(lab, 'A', 'alice') },
},
{
id: 'S13',
title: 'account linking: Alice confirms with her existing password',
run: async function (lab) {
const alice = lab.browser('A')
await visit(alice, await getCallbackUrl(lab, alice, 'alice'))
const confirmUrl = lab.client.origin + '/link/confirm'
const wrong = await visit(alice, confirmUrl, 'POST', { password: 'a-wrong-guess' })
const right = await visit(alice, confirmUrl, 'POST', { password: 'alice-lab-password' })
lab.trace.push(' (later, in a new browser, Alice signs in with the provider again)')
const later = lab.browser('A2')
const again = await visit(later, await getCallbackUrl(lab, later, 'alice'))
return { wrongPassword: wrong.status, status: right.status, response: right.body, laterSignIn: again.body }
},
},
]
// The victim's code leaks before it is used (RFC 9700 4.5). Mallory starts
// her own sign-in and swaps Bob's code into her own callback URL.
async function injectBobsCode(lab) {
const victim = lab.browser('V')
const stolen = new URL(await getCallbackUrl(lab, victim, 'bob')).searchParams.get('code')
lab.trace.push(" (V's callback URL leaks before V opens it; M copies the code)")
const mallory = lab.browser('M')
const own = await getCallbackUrl(lab, mallory, 'mallory')
lab.trace.push(" (M swaps in V's code and keeps her own state)")
const result = await visit(mallory, replaceParameter(own, 'code', stolen))
return { status: result.status, response: result.body, afterwards: await whoIsSignedIn(lab, mallory) }
}
// A link someone else built: the client's own sign-in request with only
// redirect_uri changed.
async function tryRedirectUri(lab, path) {
const visitor = lab.browser('V')
const toProvider = await visit(visitor, lab.client.origin + '/login')
lab.trace.push(' (the test changes redirect_uri to ' + path + ' before V reaches the provider)')
const crafted = replaceParameter(toProvider.location, 'redirect_uri', lab.client.origin + path)
const result = await visit(visitor, crafted + '&lab_user=bob')
const codeSentTo = result.location ? new URL(result.location).pathname : 'nowhere'
return { status: result.status, codeSentTo: codeSentTo }
}
// ---------- Checks on the mock provider's token endpoint ----------
// These send requests straight to the mock provider's token endpoint: requests
// that RFC 6749, RFC 7636 and RFC 9700 tell a provider to refuse. They show
// the mock's answers, are the same for both client versions and say nothing
// about a real provider.
export const providerChecks = [
{ id: 'P1', title: 'code_verifier missing', challenge: true, token: { omitVerifier: true } },
{ id: 'P2', title: 'code_verifier wrong', challenge: true, token: { verifier: 'w'.repeat(43) } },
{ id: 'P3', title: 'code_verifier sent for a code issued without code_challenge', challenge: false, token: {} },
{ id: 'P4', title: 'redirect_uri at the token endpoint differs', challenge: true, token: { redirectPath: '/callback/old' } },
{ id: 'P5', title: 'the same code redeemed twice', challenge: true, token: { twice: true } },
]
export async function runProviderCheck(lab, check) {
const verifier = 'v'.repeat(43)
const authoriseUrl = new URL(lab.provider.issuer + '/authorise')
const fields = { response_type: 'code', client_id: CLIENT_ID, redirect_uri: lab.client.redirectUri, scope: 'openid', lab_user: 'bob' }
if (check.challenge) Object.assign(fields, { code_challenge: sha256Base64url(verifier), code_challenge_method: 'S256' })
for (const name of Object.keys(fields)) authoriseUrl.searchParams.set(name, fields[name])
const issued = await visit(lab.browser('T'), authoriseUrl.toString())
const form = {
grant_type: 'authorization_code',
code: new URL(issued.location).searchParams.get('code'),
redirect_uri: lab.client.origin + (check.token.redirectPath || '/callback'),
}
if (!check.token.omitVerifier) form.code_verifier = check.token.verifier || verifier
await postToken(lab, form)
if (check.token.twice) await postToken(lab, form)
}
async function postToken(lab, form) {
const credential = Buffer.from(CLIENT_ID + ':' + CLIENT_SECRET).toString('base64')
const response = await fetch(lab.provider.issuer + '/token', {
method: 'POST',
headers: { authorization: 'Basic ' + credential, 'content-type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams(form).toString(),
})
await response.text()
}
function sha256Base64url(text) {
return createHash('sha256').update(text, 'ascii').digest('base64url')
}
================================================================
FILE 5 OF 6: run-scenarios.mjs
================================================================
// run-scenarios.mjs: runs every scenario against the flawed client and then
// the fixed client, printing each request in order and the result.
// Run: node run-scenarios.mjs
import { providerChecks, runProviderCheck, scenarios, startLab } from './scenarios.mjs'
function describeSettings(settings) {
const off = Object.keys(settings || {})
return off.length ? 'mock provider with ' + off.join(', ') + ' switched off' : 'mock provider with every check on'
}
function describeOutcome(outcome) {
return Object.keys(outcome).map(function (key) { return key + ': ' + outcome[key] }).join(' | ')
}
async function runOne(scenario, version) {
const lab = await startLab(version, scenario.providerSettings)
try {
const outcome = await scenario.run(lab)
console.log(' ' + version.toUpperCase())
for (const line of lab.trace) console.log(line)
console.log(' RESULT ' + describeOutcome(outcome))
} finally {
lab.close()
}
}
async function main() {
for (const scenario of scenarios) {
console.log(scenario.id + ' ' + scenario.title + ' (' + describeSettings(scenario.providerSettings) + ')')
await runOne(scenario, 'flawed')
await runOne(scenario, 'fixed')
console.log('')
}
console.log('Token endpoint checks on the mock provider (the same for both client versions)')
for (const check of providerChecks) {
const lab = await startLab('fixed', {})
try {
await runProviderCheck(lab, check)
console.log(check.id + ' ' + check.title)
for (const line of lab.trace) console.log(line)
} finally {
lab.close()
}
}
}
main()
================================================================
FILE 6 OF 6: callback.test.mjs
================================================================
// callback.test.mjs: the regression test. Every scenario except the baseline
// fails against the flawed client and passes against the fixed one.
// Run: node callback.test.mjs (the fixed client: all tests pass)
// node callback.test.mjs flawed (the flawed client: twelve tests fail)
import assert from 'node:assert/strict'
import { test } from 'node:test'
import { scenarios, startLab } from './scenarios.mjs'
const version = process.argv[2] || 'fixed'
if (!['fixed', 'flawed'].includes(version)) throw new Error('Use fixed or flawed')
const NOT_SIGNED_IN = 'not signed in'
// What the fixed client must do in each scenario.
const expectations = {
S1: function (outcome) {
assert.equal(outcome.status, 200)
assert.equal(outcome.afterwards, 'signed in as bob@example.com')
},
S2: function (outcome) {
assert.equal(outcome.status, 400)
assert.equal(outcome.afterwards, NOT_SIGNED_IN)
},
S3: function (outcome) {
assert.equal(outcome.status, 400)
assert.equal(outcome.afterwards, NOT_SIGNED_IN)
},
S4: function (outcome) {
assert.equal(outcome.status, 400)
assert.equal(outcome.afterwards, NOT_SIGNED_IN)
},
S5: function (outcome) {
assert.equal(outcome.status, 400)
assert.equal(outcome.afterwards, NOT_SIGNED_IN)
},
S6: function (outcome) {
assert.equal(outcome.sent, 'state, nonce, code_challenge, code_challenge_method')
assert.equal(outcome.method, 'S256')
},
S7: function (outcome) {
assert.equal(outcome.status, 400)
assert.equal(outcome.afterwards, NOT_SIGNED_IN)
},
S8: function (outcome) {
assert.equal(outcome.status, 400)
assert.equal(outcome.codeSentTo, 'nowhere')
},
S9: function (outcome) {
assert.equal(outcome.status, 400)
assert.equal(outcome.codeSentTo, 'nowhere')
},
S10: function (outcome) {
assert.equal(outcome.firstVisit, 200)
assert.equal(outcome.status, 400)
},
S11: function (outcome) {
assert.equal(outcome.status, 403)
assert.equal(outcome.afterwards, NOT_SIGNED_IN)
},
S12: function (outcome) {
assert.equal(outcome.status, 200)
assert.equal(outcome.afterwards, NOT_SIGNED_IN)
},
S13: function (outcome) {
assert.equal(outcome.wrongPassword, 403)
assert.equal(outcome.status, 200)
assert.equal(outcome.laterSignIn, 'signed in as alice@example.com')
},
}
for (const scenario of scenarios) {
test(scenario.id + ' ' + scenario.title, async function () {
const lab = await startLab(version, scenario.providerSettings)
try {
expectations[scenario.id](await scenario.run(lab))
} finally {
lab.close()
}
})
}
================================================================
PART 3: EVERY SCENARIO AGAINST BOTH VERSIONS
================================================================
Each scenario starts a fresh mock provider and a fresh application, so no scenario sees another's accounts, codes or sessions. Requests are shown by parameter name only, never by value. Lines in parentheses are the scenario explaining what it does next. In checks P1 to P5, browser T is the test script getting a code for itself, and its token requests go straight to the mock provider.
Command: node run-scenarios.mjs
S1 Baseline: Bob signs in for the first time (mock provider with every check on)
FLAWED
browser B: GET client /login
302 to provider /authorise ?response_type, client_id, redirect_uri, scope
browser B: GET provider /authorise (the address above, signs in at the provider as bob)
302 to client /callback ?code
browser B: GET client /callback (the address above)
back channel: POST provider /token (grant_type, code, redirect_uri, client credential)
200 access token and ID token issued
200 signed in as bob@example.com
browser B: GET client /me
200 signed in as bob@example.com
RESULT status: 200 | response: signed in as bob@example.com | afterwards: signed in as bob@example.com
FIXED
browser B: GET client /login
302 to provider /authorise ?response_type, client_id, redirect_uri, scope, state, nonce, code_challenge, code_challenge_method
browser B: GET provider /authorise (the address above, signs in at the provider as bob)
302 to client /callback ?code, state
browser B: GET client /callback (the address above)
back channel: POST provider /token (grant_type, code, redirect_uri, code_verifier, client credential)
200 access token and ID token issued
200 signed in as bob@example.com
browser B: GET client /me
200 signed in as bob@example.com
RESULT status: 200 | response: signed in as bob@example.com | afterwards: signed in as bob@example.com
S2 state missing from the callback (mock provider with every check on)
FLAWED
browser B: GET client /login
302 to provider /authorise ?response_type, client_id, redirect_uri, scope
browser B: GET provider /authorise (the address above, signs in at the provider as bob)
302 to client /callback ?code
(the test removes state from the callback URL)
browser B: GET client /callback (the address above)
back channel: POST provider /token (grant_type, code, redirect_uri, client credential)
200 access token and ID token issued
200 signed in as bob@example.com
browser B: GET client /me
200 signed in as bob@example.com
RESULT status: 200 | response: signed in as bob@example.com | afterwards: signed in as bob@example.com
FIXED
browser B: GET client /login
302 to provider /authorise ?response_type, client_id, redirect_uri, scope, state, nonce, code_challenge, code_challenge_method
browser B: GET provider /authorise (the address above, signs in at the provider as bob)
302 to client /callback ?code, state
(the test removes state from the callback URL)
browser B: GET client /callback ?code
400 refused: state missing
browser B: GET client /me
401 not signed in
RESULT status: 400 | response: refused: state missing | afterwards: not signed in
S3 state from another browser: login CSRF (mock provider with every check on)
FLAWED
browser M: GET client /login
302 to provider /authorise ?response_type, client_id, redirect_uri, scope
browser M: GET provider /authorise (the address above, signs in at the provider as mallory)
302 to client /callback ?code
(M stops before the callback and gets V to open it)
browser V: GET client /login
302 to provider /authorise ?response_type, client_id, redirect_uri, scope
browser V: GET client /callback ?code
back channel: POST provider /token (grant_type, code, redirect_uri, client credential)
200 access token and ID token issued
200 signed in as mallory@example.net
browser V: GET client /me
200 signed in as mallory@example.net
RESULT status: 200 | response: signed in as mallory@example.net | afterwards: signed in as mallory@example.net
FIXED
browser M: GET client /login
302 to provider /authorise ?response_type, client_id, redirect_uri, scope, state, nonce, code_challenge, code_challenge_method
browser M: GET provider /authorise (the address above, signs in at the provider as mallory)
302 to client /callback ?code, state
(M stops before the callback and gets V to open it)
browser V: GET client /login
302 to provider /authorise ?response_type, client_id, redirect_uri, scope, state, nonce, code_challenge, code_challenge_method
browser V: GET client /callback ?code, state
400 refused: state does not match this browser
browser V: GET client /me
401 not signed in
RESULT status: 400 | response: refused: state does not match this browser | afterwards: not signed in
S4 nonce missing from the ID token (mock provider with includeNonce switched off)
FLAWED
browser B: GET client /login
302 to provider /authorise ?response_type, client_id, redirect_uri, scope
browser B: GET provider /authorise (the address above, signs in at the provider as bob)
302 to client /callback ?code
browser B: GET client /callback (the address above)
back channel: POST provider /token (grant_type, code, redirect_uri, client credential)
200 access token and ID token issued
200 signed in as bob@example.com
browser B: GET client /me
200 signed in as bob@example.com
RESULT status: 200 | response: signed in as bob@example.com | afterwards: signed in as bob@example.com
FIXED
browser B: GET client /login
302 to provider /authorise ?response_type, client_id, redirect_uri, scope, state, nonce, code_challenge, code_challenge_method
browser B: GET provider /authorise (the address above, signs in at the provider as bob)
302 to client /callback ?code, state
browser B: GET client /callback (the address above)
back channel: POST provider /token (grant_type, code, redirect_uri, code_verifier, client credential)
200 access token and ID token issued
400 refused: nonce missing from ID token
browser B: GET client /me
401 not signed in
RESULT status: 400 | response: refused: nonce missing from ID token | afterwards: not signed in
S5 nonce from another sign-in: Bob's code in Mallory's browser, PKCE not enforced (mock provider with enforcePkce switched off)
FLAWED
browser V: GET client /login
302 to provider /authorise ?response_type, client_id, redirect_uri, scope
browser V: GET provider /authorise (the address above, signs in at the provider as bob)
302 to client /callback ?code
(V's callback URL leaks before V opens it; M copies the code)
browser M: GET client /login
302 to provider /authorise ?response_type, client_id, redirect_uri, scope
browser M: GET provider /authorise (the address above, signs in at the provider as mallory)
302 to client /callback ?code
(M swaps in V's code and keeps her own state)
browser M: GET client /callback ?code
back channel: POST provider /token (grant_type, code, redirect_uri, client credential)
200 access token and ID token issued
200 signed in as bob@example.com
browser M: GET client /me
200 signed in as bob@example.com
RESULT status: 200 | response: signed in as bob@example.com | afterwards: signed in as bob@example.com
FIXED
browser V: GET client /login
302 to provider /authorise ?response_type, client_id, redirect_uri, scope, state, nonce, code_challenge, code_challenge_method
browser V: GET provider /authorise (the address above, signs in at the provider as bob)
302 to client /callback ?code, state
(V's callback URL leaks before V opens it; M copies the code)
browser M: GET client /login
302 to provider /authorise ?response_type, client_id, redirect_uri, scope, state, nonce, code_challenge, code_challenge_method
browser M: GET provider /authorise (the address above, signs in at the provider as mallory)
302 to client /callback ?code, state
(M swaps in V's code and keeps her own state)
browser M: GET client /callback ?code, state
back channel: POST provider /token (grant_type, code, redirect_uri, code_verifier, client credential)
200 access token and ID token issued
400 refused: nonce does not match this sign-in
browser M: GET client /me
401 not signed in
RESULT status: 400 | response: refused: nonce does not match this sign-in | afterwards: not signed in
S6 PKCE: the sign-in request carries state, nonce and an S256 code_challenge (mock provider with every check on)
FLAWED
browser B: GET client /login
302 to provider /authorise ?response_type, client_id, redirect_uri, scope
RESULT sent: none of them | method: none
FIXED
browser B: GET client /login
302 to provider /authorise ?response_type, client_id, redirect_uri, scope, state, nonce, code_challenge, code_challenge_method
RESULT sent: state, nonce, code_challenge, code_challenge_method | method: S256
S7 PKCE: Bob's code in Mallory's browser, provider enforcing PKCE (mock provider with every check on)
FLAWED
browser V: GET client /login
302 to provider /authorise ?response_type, client_id, redirect_uri, scope
browser V: GET provider /authorise (the address above, signs in at the provider as bob)
302 to client /callback ?code
(V's callback URL leaks before V opens it; M copies the code)
browser M: GET client /login
302 to provider /authorise ?response_type, client_id, redirect_uri, scope
browser M: GET provider /authorise (the address above, signs in at the provider as mallory)
302 to client /callback ?code
(M swaps in V's code and keeps her own state)
browser M: GET client /callback ?code
back channel: POST provider /token (grant_type, code, redirect_uri, client credential)
200 access token and ID token issued
200 signed in as bob@example.com
browser M: GET client /me
200 signed in as bob@example.com
RESULT status: 200 | response: signed in as bob@example.com | afterwards: signed in as bob@example.com
FIXED
browser V: GET client /login
302 to provider /authorise ?response_type, client_id, redirect_uri, scope, state, nonce, code_challenge, code_challenge_method
browser V: GET provider /authorise (the address above, signs in at the provider as bob)
302 to client /callback ?code, state
(V's callback URL leaks before V opens it; M copies the code)
browser M: GET client /login
302 to provider /authorise ?response_type, client_id, redirect_uri, scope, state, nonce, code_challenge, code_challenge_method
browser M: GET provider /authorise (the address above, signs in at the provider as mallory)
302 to client /callback ?code, state
(M swaps in V's code and keeps her own state)
browser M: GET client /callback ?code, state
back channel: POST provider /token (grant_type, code, redirect_uri, code_verifier, client credential)
400 invalid_grant: code_verifier does not match code_challenge
400 refused: token endpoint said invalid_grant
browser M: GET client /me
401 not signed in
RESULT status: 400 | response: refused: token endpoint said invalid_grant | afterwards: not signed in
S8 redirect_uri with a different path (mock provider with every check on)
FLAWED
browser V: GET client /login
302 to provider /authorise ?response_type, client_id, redirect_uri, scope
(the test changes redirect_uri to /callback/old before V reaches the provider)
browser V: GET provider /authorise ?response_type, client_id, redirect_uri, scope (signs in at the provider as bob)
302 to client /callback/old ?code
RESULT status: 302 | codeSentTo: /callback/old
FIXED
browser V: GET client /login
302 to provider /authorise ?response_type, client_id, redirect_uri, scope, state, nonce, code_challenge, code_challenge_method
(the test changes redirect_uri to /callback/old before V reaches the provider)
browser V: GET provider /authorise ?response_type, client_id, redirect_uri, scope, state, nonce, code_challenge, code_challenge_method (signs in at the provider as bob)
400 error page: redirect_uri is not registered for this client
RESULT status: 400 | codeSentTo: nowhere
S9 redirect_uri with an added query (mock provider with every check on)
FLAWED
browser V: GET client /login
302 to provider /authorise ?response_type, client_id, redirect_uri, scope
(the test changes redirect_uri to /callback?next=/admin before V reaches the provider)
browser V: GET provider /authorise ?response_type, client_id, redirect_uri, scope (signs in at the provider as bob)
302 to client /callback ?next, code
RESULT status: 302 | codeSentTo: /callback
FIXED
browser V: GET client /login
302 to provider /authorise ?response_type, client_id, redirect_uri, scope, state, nonce, code_challenge, code_challenge_method
(the test changes redirect_uri to /callback?next=/admin before V reaches the provider)
browser V: GET provider /authorise ?response_type, client_id, redirect_uri, scope, state, nonce, code_challenge, code_challenge_method (signs in at the provider as bob)
400 error page: redirect_uri is not registered for this client
RESULT status: 400 | codeSentTo: nowhere
S10 the same callback URL opened twice (mock provider with singleUseCodes switched off)
FLAWED
browser B: GET client /login
302 to provider /authorise ?response_type, client_id, redirect_uri, scope
browser B: GET provider /authorise (the address above, signs in at the provider as bob)
302 to client /callback ?code
browser B: GET client /callback (the address above)
back channel: POST provider /token (grant_type, code, redirect_uri, client credential)
200 access token and ID token issued
200 signed in as bob@example.com
(the same URL again, as from the browser history)
browser B: GET client /callback ?code
back channel: POST provider /token (grant_type, code, redirect_uri, client credential)
200 access token and ID token issued
200 signed in as bob@example.com
RESULT firstVisit: 200 | status: 200 | response: signed in as bob@example.com
FIXED
browser B: GET client /login
302 to provider /authorise ?response_type, client_id, redirect_uri, scope, state, nonce, code_challenge, code_challenge_method
browser B: GET provider /authorise (the address above, signs in at the provider as bob)
302 to client /callback ?code, state
browser B: GET client /callback (the address above)
back channel: POST provider /token (grant_type, code, redirect_uri, code_verifier, client credential)
200 access token and ID token issued
200 signed in as bob@example.com
(the same URL again, as from the browser history)
browser B: GET client /callback ?code, state
400 refused: no open sign-in attempt in this browser
RESULT firstVisit: 200 | status: 400 | response: refused: no open sign-in attempt in this browser
S11 account linking: an unverified email matches a local account (mock provider with every check on)
FLAWED
browser M: GET client /login
302 to provider /authorise ?response_type, client_id, redirect_uri, scope
browser M: GET provider /authorise (the address above, signs in at the provider as mallory-alias)
302 to client /callback ?code
browser M: GET client /callback (the address above)
back channel: POST provider /token (grant_type, code, redirect_uri, client credential)
200 access token and ID token issued
200 signed in as alice@example.com
browser M: GET client /me
200 signed in as alice@example.com
RESULT status: 200 | response: signed in as alice@example.com | afterwards: signed in as alice@example.com
FIXED
browser M: GET client /login
302 to provider /authorise ?response_type, client_id, redirect_uri, scope, state, nonce, code_challenge, code_challenge_method
browser M: GET provider /authorise (the address above, signs in at the provider as mallory-alias)
302 to client /callback ?code, state
browser M: GET client /callback (the address above)
back channel: POST provider /token (grant_type, code, redirect_uri, code_verifier, client credential)
200 access token and ID token issued
403 refused: the provider has not verified this email, nothing linked
browser M: GET client /me
401 not signed in
RESULT status: 403 | response: refused: the provider has not verified this email, nothing linked | afterwards: not signed in
S12 account linking: a verified email matches a local account (mock provider with every check on)
FLAWED
browser A: GET client /login
302 to provider /authorise ?response_type, client_id, redirect_uri, scope
browser A: GET provider /authorise (the address above, signs in at the provider as alice)
302 to client /callback ?code
browser A: GET client /callback (the address above)
back channel: POST provider /token (grant_type, code, redirect_uri, client credential)
200 access token and ID token issued
200 signed in as alice@example.com
browser A: GET client /me
200 signed in as alice@example.com
RESULT status: 200 | response: signed in as alice@example.com | afterwards: signed in as alice@example.com
FIXED
browser A: GET client /login
302 to provider /authorise ?response_type, client_id, redirect_uri, scope, state, nonce, code_challenge, code_challenge_method
browser A: GET provider /authorise (the address above, signs in at the provider as alice)
302 to client /callback ?code, state
browser A: GET client /callback (the address above)
back channel: POST provider /token (grant_type, code, redirect_uri, code_verifier, client credential)
200 access token and ID token issued
200 not signed in: sign in to your existing account to confirm the link
browser A: GET client /me
401 not signed in
RESULT status: 200 | response: not signed in: sign in to your existing account to confirm the link | afterwards: not signed in
S13 account linking: Alice confirms with her existing password (mock provider with every check on)
FLAWED
browser A: GET client /login
302 to provider /authorise ?response_type, client_id, redirect_uri, scope
browser A: GET provider /authorise (the address above, signs in at the provider as alice)
302 to client /callback ?code
browser A: GET client /callback (the address above)
back channel: POST provider /token (grant_type, code, redirect_uri, client credential)
200 access token and ID token issued
200 signed in as alice@example.com
browser A: POST client /link/confirm
404 not-found
browser A: POST client /link/confirm
404 not-found
(later, in a new browser, Alice signs in with the provider again)
browser A2: GET client /login
302 to provider /authorise ?response_type, client_id, redirect_uri, scope
browser A2: GET provider /authorise (the address above, signs in at the provider as alice)
302 to client /callback ?code
browser A2: GET client /callback (the address above)
back channel: POST provider /token (grant_type, code, redirect_uri, client credential)
200 access token and ID token issued
200 signed in as alice@example.com
RESULT wrongPassword: 404 | status: 404 | response: not-found | laterSignIn: signed in as alice@example.com
FIXED
browser A: GET client /login
302 to provider /authorise ?response_type, client_id, redirect_uri, scope, state, nonce, code_challenge, code_challenge_method
browser A: GET provider /authorise (the address above, signs in at the provider as alice)
302 to client /callback ?code, state
browser A: GET client /callback (the address above)
back channel: POST provider /token (grant_type, code, redirect_uri, code_verifier, client credential)
200 access token and ID token issued
200 not signed in: sign in to your existing account to confirm the link
browser A: POST client /link/confirm
403 refused: wrong password, nothing linked
browser A: POST client /link/confirm
200 signed in as alice@example.com
(later, in a new browser, Alice signs in with the provider again)
browser A2: GET client /login
302 to provider /authorise ?response_type, client_id, redirect_uri, scope, state, nonce, code_challenge, code_challenge_method
browser A2: GET provider /authorise (the address above, signs in at the provider as alice)
302 to client /callback ?code, state
browser A2: GET client /callback (the address above)
back channel: POST provider /token (grant_type, code, redirect_uri, code_verifier, client credential)
200 access token and ID token issued
200 signed in as alice@example.com
RESULT wrongPassword: 403 | status: 200 | response: signed in as alice@example.com | laterSignIn: signed in as alice@example.com
Token endpoint checks on the mock provider (the same for both client versions)
P1 code_verifier missing
browser T: GET provider /authorise ?response_type, client_id, redirect_uri, scope, code_challenge, code_challenge_method (signs in at the provider as bob)
302 to client /callback ?code
back channel: POST provider /token (grant_type, code, redirect_uri, client credential)
400 invalid_grant: code_verifier missing
P2 code_verifier wrong
browser T: GET provider /authorise ?response_type, client_id, redirect_uri, scope, code_challenge, code_challenge_method (signs in at the provider as bob)
302 to client /callback ?code
back channel: POST provider /token (grant_type, code, redirect_uri, code_verifier, client credential)
400 invalid_grant: code_verifier does not match code_challenge
P3 code_verifier sent for a code issued without code_challenge
browser T: GET provider /authorise ?response_type, client_id, redirect_uri, scope (signs in at the provider as bob)
302 to client /callback ?code
back channel: POST provider /token (grant_type, code, redirect_uri, code_verifier, client credential)
400 invalid_grant: code_verifier sent but no code_challenge was
P4 redirect_uri at the token endpoint differs
browser T: GET provider /authorise ?response_type, client_id, redirect_uri, scope, code_challenge, code_challenge_method (signs in at the provider as bob)
302 to client /callback ?code
back channel: POST provider /token (grant_type, code, redirect_uri, code_verifier, client credential)
400 invalid_grant: redirect_uri differs from the authorisation request
P5 the same code redeemed twice
browser T: GET provider /authorise ?response_type, client_id, redirect_uri, scope, code_challenge, code_challenge_method (signs in at the provider as bob)
302 to client /callback ?code
back channel: POST provider /token (grant_type, code, redirect_uri, code_verifier, client credential)
200 access token and ID token issued
back channel: POST provider /token (grant_type, code, redirect_uri, code_verifier, client credential)
400 invalid_grant: code already used
Exit code: 0
Reading the evidence:
S1 Both versions sign Bob in. The baseline has to work before any refusal means anything.
S2, S3 The flawed version accepts a callback with no state, and in S3 signs browser V in as Mallory: login CSRF. The fixed version refuses both, and V is not signed in.
S4 With the nonce left out of the ID Token, the fixed version refuses, because a nonce it sent did not come back.
S5 With PKCE enforcement off at the mock provider, the flawed version signs Mallory's browser in as Bob from Bob's code. The fixed version refuses on the nonce alone.
S6 Only the fixed version sends state, a nonce and an S256 code_challenge.
S7 With PKCE enforced, the provider answers invalid_grant to the fixed version. The flawed version sent no code_challenge, so nothing ties Bob's code to Bob's browser, and Mallory is signed in as Bob.
S8, S9 With a pattern registered, the mock provider sends Bob's code to /callback/old and to /callback with an extra next parameter. With the exact URI registered, it shows an error page and sends the code nowhere.
S10 With single-use codes off at the mock provider, the flawed version signs Bob in twice from one URL. The fixed version refuses the second visit itself, before any request to the token endpoint.
S11 The flawed version signs Mallory into Alice's local account, because Mallory's unverified provider account claims Alice's address. The fixed version links nothing.
S12, S13 The flawed version signs Alice straight in to the local account with no confirmation. The fixed version links her provider account only after she signs in with her existing password, and from then on finds her by iss and sub.
P1 to P5 The mock provider's token endpoint refuses each request the specifications tell a provider to refuse. These rows describe the mock, not any real provider.
================================================================
PART 4: THE REGRESSION TEST
================================================================
The test runs every scenario and asserts what the fixed version must do. Run it in the pipeline that deploys your application.
Command: node callback.test.mjs
✔ S1 Baseline: Bob signs in for the first time (96.466292ms)
✔ S2 state missing from the callback (69.757833ms)
✔ S3 state from another browser: login CSRF (61.713958ms)
✔ S4 nonce missing from the ID token (49.395042ms)
✔ S5 nonce from another sign-in: Bob's code in Mallory's browser, PKCE not enforced (53.134541ms)
✔ S6 PKCE: the sign-in request carries state, nonce and an S256 code_challenge (66.669041ms)
✔ S7 PKCE: Bob's code in Mallory's browser, provider enforcing PKCE (59.99025ms)
✔ S8 redirect_uri with a different path (64.355833ms)
✔ S9 redirect_uri with an added query (33.09375ms)
✔ S10 the same callback URL opened twice (68.382542ms)
✔ S11 account linking: an unverified email matches a local account (44.331ms)
✔ S12 account linking: a verified email matches a local account (69.311667ms)
✔ S13 account linking: Alice confirms with her existing password (107.358833ms)
ℹ tests 13
ℹ suites 0
ℹ pass 13
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 847.2065
Exit code: 0
Command: node callback.test.mjs flawed
✔ S1 Baseline: Bob signs in for the first time (83.454ms)
✖ S2 state missing from the callback (86.252791ms)
✖ S3 state from another browser: login CSRF (51.493583ms)
✖ S4 nonce missing from the ID token (102.164083ms)
✖ S5 nonce from another sign-in: Bob's code in Mallory's browser, PKCE not enforced (53.792875ms)
✖ S6 PKCE: the sign-in request carries state, nonce and an S256 code_challenge (51.650125ms)
✖ S7 PKCE: Bob's code in Mallory's browser, provider enforcing PKCE (50.500333ms)
✖ S8 redirect_uri with a different path (88.972875ms)
✖ S9 redirect_uri with an added query (53.403625ms)
✖ S10 the same callback URL opened twice (112.199917ms)
✖ S11 account linking: an unverified email matches a local account (69.789666ms)
✖ S12 account linking: a verified email matches a local account (61.08975ms)
✖ S13 account linking: Alice confirms with her existing password (82.575791ms)
ℹ tests 13
ℹ suites 0
ℹ pass 1
ℹ fail 12
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 950.604333
✖ failing tests:
test at callback.test.mjs:72:3
✖ S2 state missing from the callback (86.252791ms)
AssertionError [ERR_ASSERTION]: Expected values to be strictly equal:
200 !== 400
(lines naming local file paths left out here)
at process.processTicksAndRejections (node:internal/process/task_queues:104:5)
at async Test.run (node:internal/test_runner/test:1208:7)
at async Test.processPendingSubtests (node:internal/test_runner/test:831:7) {
generatedMessage: true,
code: 'ERR_ASSERTION',
actual: 200,
expected: 400,
operator: 'strictEqual',
diff: 'simple'
}
(the details of the other 11 failing tests follow in the same form and are left out here)
Exit code: 1
The Node.js test runner sets the exit code to 1 when any test fails, so a pipeline step running this test fails if the application regresses.
================================================================
PART 5: POINT THE TESTS AT YOUR OWN APPLICATION
================================================================
1. Keep mock-provider.mjs as the provider. It is what lets a test hand your callback a leaked code, an ID Token without a nonce or an unverified email address on demand.
2. In place of lab-client.mjs, start your own application on a test port, with its provider settings pointed at the mock's issuer address and the lab's client ID and secret. If your sign-in library reads the provider's settings from a discovery document or its keys from a key set address, add those two routes to the mock first. Give the test build a route like /me that reports who is signed in, or change whoIsSignedIn in scenarios.mjs to read your own.
3. Keep scenarios S1 to S7 and S10 to S13, which exercise your callback, and change the expected messages to your application's own.
4. Scenarios S8 and S9 and checks P1 to P5 exercise the provider. For a real provider, check those through your client's registration in the provider's console and the provider's documentation, not by sending crafted requests to its service.
5. Run the tests only against an application you own or are authorised in writing to test, with invented test users, never against real customers' accounts.What happens when someone clicks "Sign in with"
A "Sign in with" button hands the job of checking who someone is to another service, the provider.
Two standards sit behind it. OAuth 2.0, which the IETF published as RFC 6749, lets an application get access to something on a person's behalf. OpenID Connect, from the OpenID Foundation, builds on that flow so the application also learns who signed in.
The same OAuth flow can be used when a business application connects to another system on a customer's behalf, such as their accounting or calendar service: delegated access, with no sign-in involved.
RFC 6749 section 4.1 describes the authorisation code flow in five steps. Your application sends the browser to the provider's authorisation endpoint with its client identifier, the access it wants (the scope), a value to keep track of the request (state) and the address to come back to (the redirect URI).
The provider authenticates the person and establishes whether they agree. If they do, it sends the browser back to that address with an authorisation code.
Your application then sends the code to the provider's token endpoint, authenticating itself as it does so, and the provider checks the code and the redirect URI before answering with an access token.
The code is what makes the design work. RFC 6749 section 1.3.1 explains that the person authenticates only with the provider, so their credentials are never shared with your application, and that the code lets the provider authenticate your application and send the access token straight to it, without passing it through the browser.
That last exchange is a server-to-server request. Every other step travels through the browser, where a value can be copied, swapped or replayed, which is why the callback, the address the browser comes back to, needs the checks this page is about.
OAuth grants access; OpenID Connect says who signed in
This distinction matters more than any other on the page.
RFC 6749 section 1.1 defines four roles: the resource owner, who can grant access; the resource server, which holds what is being accessed; the client, an application making requests on the resource owner's behalf and with their authorisation; and the authorisation server, which issues access tokens after authenticating the resource owner and obtaining authorisation.
Section 1.4 defines an access token as a string representing an authorisation issued to the client, and says the string is usually opaque to the client.
OpenID Connect Core 1.0 draws the line explicitly. Its introduction says RFC 6749 and RFC 6750 define how to obtain and use access tokens but do not define standard methods to provide identity information, and that without profiling, OAuth 2.0 is incapable of providing information about the authentication of an end-user.
The OAuth and OIDC chapter of OWASP's Application Security Verification Standard (ASVS) 5.0 says the same in fewer words: by itself, OAuth is not designed for user authentication.
OpenID Connect adds the missing piece. A client asks for it by including the openid scope value, and the provider returns an ID Token: a JSON Web Token, which the specification says MUST be signed, carrying claims about the authentication.
The required claims include the issuer (iss), a subject identifier for the person that the issuer never reassigns (sub), the audience, which MUST contain your client ID (aud), and an expiry time (exp). The specification calls the ID Token the primary extension that OpenID Connect makes to OAuth 2.0 to enable end-users to be authenticated. In its terms the provider is an OpenID Provider and your application is a relying party.
So sign people in from an ID Token you have validated, and use an access token only to call the API it was issued for. An application that takes an access token on its own as proof of who is signed in is relying on something RFC 6749 does not define.
For delegated access with no sign-in, such as letting a customer connect a calendar, plain OAuth is the right tool and the identity questions on this page do not arise, though the state, PKCE and redirect URI checks still apply.
What this guide covers, and where the neighbouring guides take over
This guide covers "Sign in with" and delegated access as a business application implements them: the authorisation code flow, the callback, and the checks that make the callback safe to accept.
Four neighbouring guides take over where it stops. The JWT security guide covers the token format itself: signature algorithms, keys and claim validation in general. The session management guide covers the session your application creates once the callback succeeds. The open redirects guide covers open redirectors, which MITRE catalogues as CWE-601, URL Redirection to Untrusted Site, and which RFC 9700 section 2.1 says clients and authorisation servers MUST NOT expose, because they can enable exfiltration of authorisation codes and access tokens. The authentication failures guide covers your own sign-in flows: passwords, recovery and account enumeration.
The values that protect the flow, in plain terms
Each value below has one job.
The asset sets out the specification section behind each one, step by step.
- state: a random value your application sends out and expects back, so the callback can tell that the browser arriving is the one that set off. RFC 6749 section 10.12 says the client MUST implement CSRF protection for its redirection URI and SHOULD use state to carry the binding value, which MUST contain a non-guessable value.
- PKCE (Proof Key for Code Exchange, RFC 7636): your application keeps a random secret, the code_verifier, sends only its SHA-256 hash, the code_challenge, at the start, and shows the secret at the end, so a code that reaches anyone else is no use to them. RFC 7636 section 4.6 says the provider MUST return an invalid_grant error when the two do not match.
- nonce: a random value your application sends at the start, which the provider copies into the ID Token, so an ID Token from any other sign-in does not match. OpenID Connect Core section 2 says that when the ID Token carries one, the client MUST verify it equals the value sent.
- The registered redirect URI: the one address the provider may send the code to, written down in advance. RFC 9700 section 2.1 says the authorisation server MUST compare redirect URIs by exact string matching, with one exception for port numbers in localhost addresses used by native apps.
- The client credential: how your application proves to the token endpoint that it is your application. Under RFC 6749 section 4.1.3, a confidential client MUST authenticate when it exchanges a code.
- The code itself: RFC 6749 section 4.1.2 says it MUST expire shortly after it is issued and that a maximum lifetime of 10 minutes is RECOMMENDED, says the client MUST NOT use it more than once, and says the authorisation server MUST deny a code used more than once.
What RFC 9700 changed
RFC 9700, the IETF's Best Current Practice for OAuth 2.0 Security (BCP 240, published January 2025), updates RFC 6749 on several of these points. It says public clients MUST use PKCE and that PKCE is RECOMMENDED for confidential clients, and adds that although PKCE was designed to protect native apps, the advice applies to all kinds of OAuth clients, including web applications.
RFC 6749 section 2.1 defines a confidential client as one capable of keeping its credentials confidential, such as a client running on a secure server with restricted access to the client credentials, or capable of secure client authentication by other means, and a public client as one that can do neither, such as an installed native application or a browser-based application.
RFC 9700 also says authorisation servers MUST support PKCE, and that clients SHOULD use a challenge method that does not expose the verifier, which it says is currently only S256.
On cross-site request forgery, RFC 9700 section 2.1 says a client that has made sure the provider supports PKCE MAY rely on it, notes that in OpenID Connect flows the nonce provides the protection, and says that otherwise one-time-use state values securely bound to the browser MUST be used.
Section 2.1.2 says clients SHOULD NOT use the implicit grant, which returns an access token in the authorisation response itself, unless access token injection in the authorisation response is prevented and the token leakage risks it describes are mitigated, and section 2.4 says the resource owner password credentials grant, which exposes the person's credentials to the application, MUST NOT be used.
This page's advice is to use all of them together: state, PKCE with S256 and, when you sign people in, the nonce. OWASP ASVS 5.0 requirement 10.1.2, at Level 2, asks the same of all three values: not guessable, specific to the transaction, and securely bound to the client and the browser session that started it.
They overlap, and in the lab the mock provider switches off one of its own checks at a time while the fixed application's check still refuses the attack.
OAuth vulnerabilities in the callback, and how to test for each
Each attack below is described at the level you need to recognise it and test for it in an application you own or are authorised in writing to test.
The scenario numbers refer to the lab in the asset, which runs every one against a flawed and a fixed version of the same application.
RFC 6749 section 10.12 describes a CSRF attack against the client's redirection URI: the attacker injects their own authorisation code or access token, which can result in the client using an access token associated with the attacker's resources rather than the victim's.
The RFC's example is the victim's bank account details being saved to a resource the attacker controls. With "Sign in with", the same move signs the victim in to the attacker's account, so whatever they then save lands there.
RFC 9700 section 4.7 calls it injecting a request to the redirection URI of the legitimate client on the victim's device, and MITRE catalogues cross-site request forgery as CWE-352.
The fix is a state value created for each sign-in attempt, stored against a cookie only this browser holds, compared when the browser returns and then thrown away. OpenID Connect Core section 3.1.2.1 says CSRF mitigation is typically done by cryptographically binding the value of state with a browser cookie; the lab keeps the value on the server against a random cookie, which ties it to the browser the same way.
Test it two ways: remove state from a genuine callback (scenario S2), and open, in one browser, a callback that another browser started (S3).
Both must be refused, and the second browser must not end up signed in. The CSRF guide covers forged requests in general; this is the form aimed at the callback.
Authorisation codes can leak. RFC 9700 describes them reaching attackers through loosely checked redirect URIs (section 4.1), Referer headers (section 4.2) and browser history (section 4.3). Section 4.5 describes what an attacker does with one. They start an ordinary sign-in with your application from their own browser, swap the victim's code into the response coming back, and let your application redeem it.
Your application authenticates to the token endpoint with its own credential, the provider sees a valid code issued to your client, and the attacker's session is now attached to the victim's identity.
RFC 9700 notes that even asymmetric client authentication does not stop this, because the legitimate client is the one authenticating.
PKCE is one of the two solutions RFC 9700 section 4.5.3 calls good technical solutions. The injected code is tied to the code_challenge from the victim's sign-in, but your application sends the verifier from the attacker's sign-in, so the check fails. In scenario S7 the mock provider answers invalid_grant to the fixed application, while the flawed application, which never sent a code_challenge, signs the attacker in as Bob.
Scenario S6 checks the simpler thing first: that every sign-in request carries a code_challenge with the S256 method, which RFC 7636 section 4.2 says a client capable of S256 MUST use.
PKCE only helps if the provider enforces it. RFC 9700 section 2.1.1 says that when a client sends a valid code_challenge, the authorisation server MUST enforce the correct use of code_verifier at the token endpoint, and section 4.8.2 says it MUST reject a token request that carries a code_verifier for a code issued without a code_challenge, which closes what the RFC calls a PKCE downgrade attack.
Checks P1 to P3 show the mock provider giving those answers. For a real provider, confirm them from its documentation and from any setting that makes PKCE required for your client.
A signature check stops a forged ID Token. The nonce deals with a genuine one from a different sign-in. OpenID Connect Core section 2 describes the nonce as a value used to associate a client session with an ID Token and to mitigate replay attacks.
Section 3.1.3.7 says that if a nonce was sent in the authentication request, a nonce claim MUST be present in the ID Token and its value checked against the one sent, and that the client SHOULD check the nonce value for replay attacks.
OWASP ASVS 5.0 requirement 10.5.1, at Level 2, asks the client to mitigate ID Token replay, for example by matching the nonce in this way.
RFC 9700 section 4.5.3.2 explains how this also protects OpenID Connect clients against code injection: the nonce stored in the session where the code is injected does not match the nonce in the ID Token issued for that code. It attaches two MUSTs for a client relying on it: validate the nonce in the ID Token obtained from the token endpoint, and disregard every token, ID Token and access token alike, until that check succeeds.
It also says the nonce does not protect codes issued to public clients, because an attacker can take a stolen code straight to the token endpoint.
Scenario S5 switches PKCE enforcement off in the mock provider and shows the fixed application refusing the injected code on the nonce alone.
Generate the nonce fresh for each sign-in attempt. OpenID Connect Core section 3.1.2.1 says sufficient entropy MUST be present in nonce values to prevent attackers from guessing them, and section 15.5.2 suggests, for web server clients, storing a cryptographically random value in an HttpOnly session cookie and sending a cryptographic hash of it as the nonce.
In scenario S4 the mock provider leaves the nonce out of the ID Token, and the fixed application refuses, because a nonce it sent has to come back.
Some authorisation servers let a client register a pattern instead of a complete redirect URI. RFC 9700 section 4.1 says this turned out to be more complex to implement and more error-prone to manage than exact matching, that several successful attacks exploiting flaws in pattern matching, or in particular configurations, have been observed in the wild, and that insufficient validation lets an attacker obtain a code or access token, either by sending the browser straight to an address under the attacker's control or through an open redirector at the client.
Its countermeasure, in section 4.1.3, is exact matching: the authorisation server MUST ensure the two URIs are equal by simple string comparison, with variable port numbers allowed only for native apps using a localhost address.
The matching is the provider's job, but what gets matched is your registration, so register each callback URI in full, with no wildcard. Scenarios S8 and S9 send the application's own sign-in request with only redirect_uri changed, once to a different path and once with a query added. With the flawed registration, a pattern, the mock provider sends Bob's code to both addresses.
With the exact registration it shows an error page and sends the code nowhere, which is what RFC 6749 section 4.1.2.1 asks: on a mismatching redirect URI, the authorisation server SHOULD inform the person and MUST NOT automatically redirect to the invalid address.
At the token endpoint, RFC 6749 section 4.1.3 also requires, when the authorisation request carried a redirect_uri, that the token request carries it too and that the two values are identical, and check P4 shows the mock provider refusing one that differs.
An authorisation code travels in a URL, so it can be copied. RFC 9700 section 4.3.1 notes that the callback URL, code included, may end up in the browser's history, where an attacker with access to the device could obtain the code and try to replay it. RFC 6749 section 4.1.2 puts the defence on both sides: the client MUST NOT use a code more than once, and the authorisation server MUST deny a code used more than once and SHOULD revoke, when possible, all tokens already issued from it. Check P5 shows the mock provider refusing a second redemption.
Your application need not rely on the provider for this. If each sign-in attempt is deleted the moment the callback reads it, a second visit to the same callback URL is refused before any code reaches the token endpoint.
It also does what RFC 9700 section 4.2.4 says a client SHOULD do: invalidate the state value after its first use at the redirection endpoint. Scenario S10 switches single-use codes off in the mock provider: the flawed application signs Bob in a second time from the replayed URL, and the fixed one answers that there is no open sign-in attempt in that browser.
This is where an OAuth vulnerability becomes an account takeover. A business adds "Sign in with" to an application whose customers already have password accounts, and links the two whenever the email addresses match. Picture an existing customer, Alice, and someone else who opens an account at the provider with Alice's address and never proves they own it.
If your application matches on the address, that person is signed straight in to Alice's account.
MITRE's CWE-287, Improper Authentication, describes the weakness: when an actor claims to have a given identity, the product does not prove or insufficiently proves that the claim is correct.
OpenID Connect Core rules out matching on email in two places. Section 5.7 says iss and sub together are the only claims a relying party can rely on as a stable identifier, that an issuer MAY reuse an email value for different people at different times, and that claims such as email, phone_number, preferred_username and name MUST NOT be used as unique identifiers.
Section 5.1 defines email_verified: when it is true, the provider took affirmative steps to ensure the address was controlled by the person at the time the verification was performed, and the means of verification is context specific.
OWASP ASVS 5.0 requirement 10.5.2, at Level 2, asks the client to identify the user from ID Token claims that cannot be reassigned to other users.
The fixed application in the lab keys every link on iss and sub. When a new sign-in carries an email address that matches an existing account, it refuses outright if email_verified is not true (scenario S11), and when it is true it still links nothing until the person signs in to the existing account the way they always have (S12 and S13).
Even a verified address is a statement the provider made at the time it checked, under its own rules, so treat it as a reason to offer a link, not as proof of ownership.
Test with one existing local account and two provider accounts that share its address, one verified and one not: neither may arrive signed in to the existing account.
If your application offers more than one provider, RFC 9700 section 4.4 describes mix-up attacks, in which a provider under an attacker's control tricks your application into sending it a code or access token issued by an honest provider. Section 2.1 makes a defence REQUIRED when a client can interact with more than one authorisation server, and says clients SHOULD use the iss parameter from RFC 9207 or an iss value in the authorisation response, such as the one in an OpenID Connect ID Token.
RFC 9207 section 2.4 says a client supporting it MUST compare that value with the issuer the request was sent to and reject the response if they differ, and RFC 9700 section 4.4.2 says the client MUST store, for each authorisation request, the issuer it sent the request to, bound to the browser. The lab has one provider and does not test this.
Running the callback lab on your own machine
The lab is an illustration.
A mock provider with four invented users and an application with a "Sign in with" button run on your own machine, bound to 127.0.0.1 on ports the system picks, with everything kept in memory. The application comes in two versions. The flawed one sends no state, nonce or PKCE values, registers its callback as a pattern and matches accounts by email address.
The fixed one does each of those properly. Both check the ID Token's signature, issuer, audience and expiry the same way, so every difference in the results comes from the checks on this page.
It uses only what ships with Node.js, and it was written and run on Node.js 26.0.0; every output in the asset comes from that run.
Be clear about what it proves. A mock provider proves what your callback code does with a provider's answers, not what a real provider does. To isolate the application's own checks, three scenarios switch one of the mock provider's checks off: S4 leaves the nonce out of the ID Token, S5 stops enforcing PKCE and S10 lets a code be used twice. The specifications require a provider to do all three, so read those scenarios as defence in depth.
- Save the six files into an empty folder and open a terminal there. There is nothing to install.
- Run node run-scenarios.mjs. For each of the thirteen scenarios it prints every request the scripted browsers make, every server-to-server request to the token endpoint and the result, first for the flawed application and then for the fixed one, followed by five checks on the mock provider's token endpoint.
- Run node callback.test.mjs. All thirteen tests pass against the fixed application. Run node callback.test.mjs flawed and twelve fail; the Node.js test runner documentation says the process exit code is set to 1 when any test fails, so a pipeline step running the test fails too.
- Test only applications you own or are authorised in writing to test, with invented test users.
Pointing the tests at your own application
Keep the mock provider: it is what lets a test hand your callback a leaked code, an ID Token without a nonce or an unverified address on demand. Start your own application on a test port in place of lab-client.mjs, with its provider settings pointed at the mock's issuer address, and keep the scenarios that exercise your callback, S1 to S7 and S10 to S13.
If your sign-in library reads the provider's settings from a discovery document or its keys from a key set address, add those two routes to the mock first.
Scenarios S8 and S9 and checks P1 to P5 exercise the provider. For a real provider, check those through your client's registration in the provider's console and the provider's own documentation, not by sending crafted requests to its service.
Use a maintained library, and check what it is set to do
Writing the protocol yourself means getting every check in the asset right, plus the signature and key handling around them.
This page's advice is to use a maintained library for the protocol and an established provider for the authorisation server, and the sources point the same way. The ASVS 5.0 chapter on OAuth and OIDC says that, given the complexity of the area, it is vitally important for a secure OAuth or OIDC solution to use well-known industry-standard authorisation servers and apply the recommended security configuration.
The OWASP Top 10:2025 says that ideally a premade, well-trusted system handles authentication, identity and session management, and to transfer this risk whenever possible by buying and using a hardened and well tested system.
For Next.js applications, the Next.js authentication guide recommends an authentication library over a custom solution, for increased security and simplicity. The Next.js guide on this site covers the rest of that framework.
When choosing, the OpenID Foundation says its free suite of conformance tests lets developers assess how well their implementations conform to its most mature, stable standards and profiles, and implementations that complete its self-certification process can use the OpenID Certified mark. A library runs with whatever settings your application gives it, so after choosing one, check these.
- It sends state, a nonce and an S256 code_challenge on every sign-in, and checks all three on the way back (scenarios S2 to S7).
- It validates the ID Token's iss, aud, exp and nonce as OpenID Connect Core section 3.1.3.7 requires, and checks the signature with the keys the provider supplies.
- Your code finds accounts by iss and sub, never by email address, and any option to link accounts by matching email addresses is switched off or sits behind a confirmation step (S11 to S13).
- Each sign-in attempt is used once (S10).
- Tokens go only to the parts of the system that need them. ASVS 5.0 requirement 10.1.1, at Level 2, gives the example of a backend-for-frontend, where access and refresh tokens are only accessible to the backend.
- Then run the callback tests against your application with the library in place. They test the configuration you deployed, not the library in general.
What to put in a new integration's configuration
Some of these are set in the provider's console rather than in your code.
Record what you chose for each new integration, and why.
- Exact redirect URIs. List each callback in full, one per environment, with no wildcards, and remove any you no longer use. RFC 9700 section 2.1 says the authorisation server MUST use exact string matching, except for port numbers in localhost redirect URIs of native apps, and ASVS 5.0 requirement 10.4.1, at Level 1, asks for a client-specific allowlist of pre-registered URIs compared by exact string comparison. RFC 9700 section 2.6 adds that authorisation servers MUST NOT allow redirect URIs using the http scheme, except for native clients using loopback redirection.
- The narrowest scopes. Ask for openid and only the profile data and API access the feature uses. RFC 9700 section 2.3 says an access token's privileges SHOULD be restricted to the minimum required, and ASVS 5.0 requirements 10.2.3 (Level 3) and 10.4.11 (Level 2) ask the client to request, and the authorisation server to assign, only the scopes needed. Under RFC 6749 section 3.3 the authorisation server MAY ignore part or all of the scope you asked for, and MUST include the scope response parameter when what it issued differs, so read the scope that comes back.
- Grant types. Switch on the authorisation code grant and leave the others off unless a feature needs one. RFC 9700 section 2.1.2 says clients SHOULD NOT use the implicit grant unless access token injection in the authorisation response is prevented and the token leakage risks it describes are mitigated, and section 2.4 says the resource owner password credentials grant MUST NOT be used. ASVS 5.0 requirement 10.4.4, at Level 1, asks the authorisation server to allow each client only the grants it needs and says those two must no longer be used.
- PKCE required, with S256. If the provider lets you require PKCE for your client, require it. RFC 9700 section 2.1.1 says public clients MUST use PKCE and recommends it for confidential clients, and ASVS 5.0 requirement 10.4.6, at Level 2, asks the authorisation server to require it and not to accept the plain method.
- Client authentication. Keep the client secret on your server, never in browser code or a mobile app, and rotate it when someone who had access to it leaves. RFC 9700 section 2.5 says authorisation servers SHOULD enforce client authentication where feasible, and that asymmetric methods, such as mutual TLS or signed JWTs (private_key_jwt), are RECOMMENDED, because with them the authorisation server does not need to store sensitive symmetric keys.
- The number of providers. If you accept more than one, build the mix-up defence described above before launch.
OAuth 2.1 is still a draft
OAuth 2.1 gathers many of these rules into one document. When this page was reviewed, the IETF datatracker listed it as an active Internet-Draft, draft-ietf-oauth-v2-1-17, last updated on 30 October 2026, and the draft itself says an Internet-Draft should be cited only as work in progress.
Its non-normative list of changes from OAuth 2.0 includes building PKCE into the authorisation code grant, exact redirect URI matching, removing the PKCE plain method, and leaving out the implicit and resource owner password credentials grants.
The OWASP OAuth 2.0 cheat sheet already marks the implicit grant as deprecated and tells clients to use the authorisation code grant with PKCE for all client types. Until the draft is published as an RFC, configure to RFC 9700.
What to review when a provider relationship changes
Sign-in depends on settings held by two organisations, so review it whenever either side changes.
- Adding a second provider: add the mix-up defence, store with each sign-in attempt, bound to the browser, the issuer it was sent to, as RFC 9700 section 4.4.2 requires, and check that the new provider's accounts cannot link to existing local accounts by email address alone.
- Moving to a new provider, or to a new tenant at the same one: the issuer can change, and with it every iss and sub pair your links are keyed on: OpenID Connect Core section 5.7 makes sub unique within its issuer, and the pair is the stable identifier. Plan how existing customers re-link through their current sign-in method rather than matching them by email address.
- A change in how the provider verifies email addresses: OpenID Connect Core section 5.1 says the means of verification is context specific, so revisit any rule in your application that relies on email_verified.
- People leaving: rotate the client secret and remove their access to the provider's console.
- Retired environments and features: remove their redirect URIs and the scopes only they needed.
- Library and provider updates: re-run the callback tests after each upgrade of your sign-in library and each change the provider announces to its authorisation or token endpoints. RFC 9700 section 2.1.1 recommends that authorisation servers publish code_challenge_methods_supported in their metadata, which is one place to confirm PKCE support is still there.
Where an outside test fits
Your own tests cover the scenarios you thought of.
A Clever Ops web application and API penetration test covers authentication and sessions, what each role can see and change, and the API called directly rather than only through the screens. Single sign-on is scoped separately: signing in through an identity provider adds the sign-in exchange, account linking and the provider settings to test, and needs a test identity provider you control.
Each finding comes with evidence, a fix written for your stack and the criteria the retest will use. If Clever Ops built or hosts your application, the work is a security review rather than an independent test, and the report says who built it and who hosts it.
Frequently asked questions
OAuth 2.0 lets an application get access to something on a person's behalf, using an access token that RFC 6749 defines as a string representing an authorisation issued to the client. OpenID Connect adds an ID Token with claims about the authentication, which the application must validate. OpenID Connect Core says that without that profile, OAuth 2.0 is incapable of providing information about the authentication of an end-user.
Not on its own. An access token records an authorisation for your application to call an API, and RFC 6749 does not define it as a statement of who signed in. Sign people in from an ID Token you have validated, with its issuer, audience, expiry and nonce checked as OpenID Connect Core section 3.1.3.7 sets out, and find the account by the iss and sub claims together.
PKCE, Proof Key for Code Exchange (RFC 7636), ties an authorisation code to a secret that only the application that asked for the code holds, so a stolen code is no use to someone who does not hold that secret, as long as the provider enforces PKCE. It was designed for native apps, but RFC 9700 says the advice applies to all kinds of OAuth clients, including web applications: public clients MUST use it, it is RECOMMENDED for confidential clients, and clients SHOULD use a method that does not expose the verifier, which RFC 9700 says is currently only S256.
It lets your callback check that the browser arriving with a code is the one that started the sign-in. RFC 6749 says the client MUST protect its redirection URI against CSRF and SHOULD use state to carry a non-guessable value bound to the browser. RFC 9700 adds that a client that has made sure the provider supports PKCE MAY rely on PKCE for this, that in OpenID Connect flows the nonce provides it, and that otherwise one-time-use state values securely bound to the browser MUST be used.
It ties an ID Token to the sign-in attempt that asked for it. Your application sends a fresh random value, the provider copies it into the ID Token, and OpenID Connect Core says the client MUST check that the two match. RFC 9700 says confidential OpenID Connect clients MAY use it instead of PKCE against code injection, provided they validate it in the ID Token from the token endpoint and disregard every token until that check succeeds.
Not automatically. OpenID Connect Core section 5.7 says email MUST NOT be used as a unique identifier, and that an issuer MAY reuse an email address for different people at different times. Link only after the person proves they own the existing account by signing in to it, and refuse to link at all when the provider does not say the address is verified.
RFC 9700 says clients SHOULD NOT use it, or any other response type that issues access tokens in the authorisation response, unless access token injection in the authorisation response is prevented and the token leakage risks it describes are mitigated, and says clients SHOULD instead use the authorisation code grant or another response type that issues access tokens in the token response. The OAuth 2.1 Internet-Draft leaves the implicit grant out, and the OWASP OAuth 2.0 cheat sheet marks it as deprecated.
Scope the right test for your application
Tell us what you have built, who uses it and when it needs to launch. You will get a plain-English recommendation: a website audit, a web application test or a referral to a specialist.