This lesson combines 3 topics: OAuth 2.0 roles & the Authorization Code flow with a confidential client, PKCE, state, nonce: three bindings against attacks, id_token is a JWT: 7 checks & JWKS.
Learning Objectives
- Name the 4 OAuth 2.0 roles correctly and identify which role the MemberPortal BFF plays
- Understand why the BFF is a confidential client and which grant types that opens up
- Know each step of the Authorization Code flow:
/authorize→code→/oauth/token→id_token+access_token - Read the parameters of each request/response, and know which are required and which the BFF generates itself
- Describe MemberPortal's two endpoints
/auth/web/loginand/auth/web/login-callbackat the spec-table level - Understand what two things each of
code_verifier,state,noncebinds together and which attack it blocks - Generate a
code_verifieryourself with a CSPRNG and computecode_challenge = BASE64URL(SHA256(verifier))without padding - Write the correct order of checks at the callback:
statefirst, thencode, thennonceonce theid_tokenis available - Know the rule "wrong binding → delete SessionID1" and explain why
- List the concrete vulnerabilities that arise when each binding is missing
- Read the JWT structure
header.payload.signatureand explain why "readable" is not the same as "trustworthy" - List and correctly perform MemberPortal's 7 id_token checks: signature,
iss,aud,exp,nonce, custom claimconnection, conditionalauth_time - Understand JWKS:
kid, caching, rotation, retry when fetching JWKS fails - Know when
auth_timemust be checked and where the 600-second threshold comes from - Apply the principle accountNo comes from the id_token, not from the client and explain why
Part 1: OAuth 2.0 roles & the Authorization Code flow with a confidential client
1. What Days 1–2 left open, what Days 3–4 solve
Days 1–2 answered the second and third of the "three questions of every login spec": where does login state live (Redis, two kinds of session) and what happens on failure (401, which cookies to delete). The first question, who authenticates the user and how does the BFF trust that result, is still open.
MemberPortal does not check passwords itself. That job is delegated to the IdP (Auth0, with Keycloak as backup). The BFF only receives a "proof" and must validate that proof correctly. The proof is the id_token, and the way to obtain it is the Authorization Code flow of OAuth 2.0 (RFC 6749) as extended by OpenID Connect.
2. The four OAuth 2.0 roles and who is who in MemberPortal
RFC 6749 defines 4 roles. A common mistake when writing specs is to call everything a "server", which leaves readers unsure which party holds the secret and which issues tokens.
| Role (RFC 6749) | Definition | In MemberPortal |
|---|---|---|
| Resource Owner | The owner of the data, who consents to access | A customer with an online trading account |
| Client | The application requesting access on behalf of the Resource Owner | The NestJS BFF (not the browser!) |
| Authorization Server (AS) | Authenticates the Resource Owner, issues code and tokens | ACME's Auth0 tenant (or Keycloak during failover) |
| Resource Server (RS) | Holds the data, accepts access_tokens | Internal API Gateway / Core API (via the BFF), Auth0 Management API (Day 4, Part 1) |
The common confusion: the browser is not the Client. In the BFF model, the browser only carries redirects and cookies (login_sid, then sid). It never sees code_verifier, client_secret, or id_token. Precisely because the Client is a BFF running on the server, we get section 3.
3. Confidential client vs public client
RFC 6749 section 2.1 splits Clients into two types by their ability to keep client_secret secret:
| Confidential client | Public client | |
|---|---|---|
| Runs where | A server we control (BFF, backend) | The user's device (SPA, mobile app, desktop) |
Can keep client_secret? | Yes (env/SSM, never sent to the browser) | No (anyone can decompile/view the source) |
Client authentication at /oauth/token | client_id + client_secret | Only client_id (+ mandatory PKCE) |
| Usable grants | authorization_code, client_credentials, refresh_token, mfa (Auth0 extension) | authorization_code + PKCE, refresh_token (with rotation) |
| MemberPortal examples | portal-web, portal-management, the step-up clients | None: every client goes through the BFF |
MemberPortal made the BFF a confidential client for three reasons stated explicitly in the spec:
- Tokens never leave the server.
id_token/access_tokenexist only in BFF memory during the callback and (for step-up MFA) in Redis. The browser only hassid. client_credentialsis available so the BFF can call the Auth0 Management API at startup (Day 4, Part 1). Public clients do not have this grant.- PKCE is still used even though it is not mandatory for confidential clients. The OAuth 2.0 Security BCP recommends PKCE for every client; the cost is almost zero, and it blocks code injection. Day 3, Part 2 covers this in detail.
Self-check question: if tomorrow the mobile team wants to call Auth0 directly from the native app without going through the BFF, are they a public or a confidential client? Can they use
client_credentials? Why?
4. Grant types and MemberPortal's choices
| grant_type | Used by | User interaction? | Returns | MemberPortal |
|---|---|---|---|---|
authorization_code | Clients whose users log in through a browser | Yes | code → id_token, access_token, (refresh_token) | portal-web, all step-up clients |
client_credentials | Machine to machine, no user | No | access_token for the client itself | portal-management (calls the Management API) |
refresh_token | Clients that want to renew an access_token | No | New access_token | Not used: the BFF uses a Redis session with its own TTL, no refresh token needed |
http://auth0.com/oauth/grant-type/mfa-otp and the mfa-* family | Clients that need to call the MFA API after authentication | Yes | access_token with scopes enroll, read:authenticators | stepup-password-web, stepup-password-native (Day 7, Part 1) |
Implicit (response_type=token) | Legacy SPAs | Yes | Token in the URL fragment | Not used, removed in OAuth 2.1 |
| Password grant (ROPC) | Apps that collect user/pass and send them straight to the IdP | Yes | Token | Not used, lets the app see the password |
Two design questions the MemberPortal spec answers explicitly, and which you should imitate:
- Why no refresh_token? Because the "logged-in session" is the Redis session
sess:{id}with TTLSESSION_TTL; after login the access_token from the IdP is not used to call any Resource Server (the Internal API Gateway trusts the BFF session, not the Auth0 token). Keeping a refresh_token only adds one more thing to protect. - Why client_credentials when authorization_code already exists? Because the BFF has work to do outside the context of a user (reading user metadata through the Management API, changing the passkey cancel URL...). The logged-in user's token does not have enough permissions and does not exist when the BFF starts.
5. The Authorization Code flow step by step
This is the backbone of /auth/web/login → /auth/web/login-callback. Remember the four "legs" and the data passing through each.
sequenceDiagram
participant B as Browser
participant BFF as BFF (Client)
participant AS as Auth0 (AS)
B->>BFF: GET /auth/web/login?successUrl=/dashboard
Note over BFF: generate state, nonce,<br/>code_verifier (CSPRNG)<br/>store login:{sid1} in Redis
BFF-->>B: 302 Location: https://login.example.com/authorize?...<br/>(Set-Cookie login_sid)
B->>AS: GET /authorize?client_id&redirect_uri&response_type=code<br/>&scope&state&nonce&code_challenge(&method=S256)
Note over AS: user enters password
AS-->>B: 302 Location: https://portal.example.com/auth/web/<br/>login-callback?code=AUTHZ_CODE&state=STATE
B->>BFF: GET /auth/web/login-callback?code&state (cookie login_sid)
Note over BFF: read login:{sid1}, compare state
BFF->>AS: POST /oauth/token<br/>grant_type=authorization_code<br/>code, redirect_uri,<br/>client_id, client_secret,<br/>code_verifier
AS-->>BFF: { id_token, access_token,<br/>expires_in, token_type }
Note over BFF: verify id_token (Part 3)<br/>delete login:{sid1}<br/>create sess:{sid2} + xsrfToken
BFF-->>B: 302 Location: successUrl<br/>Set-Cookie: sid=sid2#59; xsrf=...#59; uid=...5.1 Leg 1: the BFF prepares and redirects to /authorize
Parameters the BFF attaches to the /authorize URL (RFC 6749 §4.1.1 + OIDC Core §3.1.2.1 + RFC 7636):
| Parameter | Required | MemberPortal value | Generated by | Notes |
|---|---|---|---|---|
response_type | Yes | code | fixed | Only receive a code, never a token directly |
client_id | Yes | id of portal-web | env IDP_CLIENT_ID | Public, not a secret |
redirect_uri | Yes (OIDC) | https://{BFF_DOMAIN}/auth/web/login-callback | fixed per env | Must exactly match the allow-list in Auth0 |
scope | Yes | openid profile | fixed | openid is required to receive an id_token |
state | Recommended (BFF: required) | CSPRNG string | BFF | Stored in login:{id}, compared at the callback |
nonce | Recommended (BFF: required) | CSPRNG string | BFF | Stored in login:{id}, compared with the nonce claim |
code_challenge | Yes (PKCE) | BASE64URL(SHA256(code_verifier)) | BFF | code_verifier is stored in login:{id} |
code_challenge_method | Yes (PKCE) | S256 | fixed | Never use plain |
connection | IdP-specific | Username-Password | fixed per client | Auth0-specific parameter that selects the connection |
prompt | No | empty (web login) / login (step-up) | per flow | Forces the IdP to re-authenticate; always paired with max_age so auth_time can be checked (Day 3, Part 3) |
max_age | No | empty (web login) / 600 (step-up) | per flow | Forces the IdP to issue the auth_time claim (OIDC Core §3.1.2.1: with max_age, auth_time is REQUIRED; without it, only OPTIONAL) |
Generating state, nonce, code_verifier and storing SessionID1 (login:{id}) is exactly the "data stored in the data store table" learned in Day 2, Part 1. If you forget why there are two kinds of session, look at the diagram again: login:{sid1} lives exactly from leg 1 to leg 3 and is then deleted; sess:{sid2} is born in leg 4.
5.2 Leg 2: the IdP authenticates and returns a code
Auth0 shows Universal Login, checks the password, checks the account type via the custom DB (Day 6, Part 2), then 302s back to redirect_uri with:
| Success | Failure |
|---|---|
?code=<authorization code>&state=<state> | ?error=access_denied&error_description=...&state=<state> |
The code is a short-lived string (by default Auth0 expires it after a few minutes), single-use, and can only be exchanged by a client with the right client_secret and the right code_verifier. The error branch is handled in Day 4, Part 2.
5.3 Leg 3: the BFF exchanges the code for tokens at /oauth/token
This is a server-to-server request; the browser is not involved. The body is application/x-www-form-urlencoded (Day 1, Part 2 mentioned why the token endpoint accepts a form, not JSON).
POST /oauth/token HTTP/1.1
Host: login.example.com
Content-Type: application/x-www-form-urlencoded
grant_type=authorization_code
&client_id=<IDP_CLIENT_ID>
&client_secret=<IDP_CLIENT_SECRET>
&code=<code from the callback>
&redirect_uri=https%3A%2F%2Fportal.example.com%2Fauth%2Fweb%2Flogin-callback
&code_verifier=<code_verifier taken from login:{id}>
Successful response:
{
"access_token": "<opaque or JWT>",
"id_token": "<JWT: header.payload.signature>",
"token_type": "Bearer",
"expires_in": 86400
}
The MemberPortal spec states: retry /oauth/token at most 2 times on 5xx/timeout; on a 4xx error (e.g. invalid_grant because the code expired) do not retry, delete login:{id}, and go to "Login failed".
5.4 Leg 4: verify and issue the session
The BFF verifies the id_token against the 7 checks (Day 3, Part 3), takes sub and the custom claim https://claims.example.com/account_no, calls the Account Attribute API and the Login Status API (Day 6, Part 2), and only then:
- Deletes
login:{sid1}. - Generates a new
sid2with a CSPRNG, generates anxsrfToken, storessess:{sid2}with TTLSESSION_TTL. - Sets the
sid,xsrf,uidcookies; 302 tosuccessUrl.
The order "verify → call business APIs → only then create the session" is deliberate: if sess were created first and a business API then failed, the spec would need an extra branch to delete the session. Creating it last means the error branch only needs "do not set cookies".
6. MemberPortal's two endpoints at the spec-table level
Day 7, Part 3 teaches the full format. Here you get a preview of a condensed version to connect theory with a real spec.
6.1 GET /auth/web/login
Overview: start the login sequence, redirect the user to the IdP.
| Location | Item | Required | Value / Rule |
|---|---|---|---|
| query | successUrl | No | Absolute URL with the same origin https://{BFF_DOMAIN} (compare scheme + host + port, reject http://); invalid → use https://www.example.com/ |
| query | failureUrl | No | Same as above |
| query | _gl | No | Tracking parameter, appended to successUrl with ? or & |
| cookie | sid | No | If a valid sess:{id} already exists → 302 straight to successUrl, skip the IdP |
Processing details:
- If
isOpe=true(operator mode) → 400 (Day 7, Part 2). - Select the IdP: Auth0 or Keycloak according to
ALT_IDP_ENABLED+ the Auth Health API (Day 6, Part 3); writeidProviderinto the session. - Generate
state,nonce,code_verifier(CSPRNG); computecode_challenge. - Create
login:{sid1}with TTLSESSION_LOGIN_TTLand the fields:state,nonce,codeVerifier,successUrl,failureUrl,idProvider,channel=Web. - Set-Cookie
login_sid=sid1(Secure, HttpOnly, Lax); 302 to/authorizewith the parameters from section 5.1.
6.2 GET /auth/web/login-callback
| Location | Item | Required | Value / Rule |
|---|---|---|---|
| cookie | login_sid | Yes | Must point to a live login:{id}; missing → "Login failed" |
| query | state | Yes | Must equal the state in login:{id} |
| query | code | Yes (when there is no error) | Exchanged at /oauth/token |
| query | error, error_description | No | If error is present → screen mapping (Day 4, Part 2) |
Processing details (condensed):
- No
login:{id}→ "Login failed", delete nothing (there is nothing to delete). - Wrong
state→ deletelogin:{id}, "Login failed". errorpresent → deletelogin:{id}, map byerror/error_description.- Missing
code→ deletelogin:{id}, "Login failed". - Token request (retry ≤ 2 times on 5xx/timeout) → fail: delete
login:{id}, "Login failed". - Verify
id_token(7 checks) → fail: deletelogin:{id}, "Login failed". - Account Attribute API / Login Status API → per Day 6, Part 2.
- Success: delete
login:{id}, createsess:{sid2}, set cookies, 302successUrl.
Important observation: every error branch after login:{id} has been read deletes it. That is the "single-use login sequence" rule: an attacker cannot try multiple state/code values against the same session sequence.
7. Common mistakes when writing an Authorization Code flow spec
| Mistake | Consequence | How MemberPortal avoids it |
|---|---|---|
| Writing "the browser calls /oauth/token" | Readers assume a public client; the secret leaks | The diagram clearly shows the browser only carries redirects |
Omitting redirect_uri from the token request | Auth0 rejects with invalid_grant when it differs from /authorize | The token request parameter table includes redirect_uri |
scope without openid | No id_token, only an opaque access_token | Fixed to openid profile |
Using code_challenge_method=plain | PKCE is pointless if /authorize is logged | Fixed to S256 |
Not stating that code is single-use | Testers do not understand why refreshing (F5) the callback fails | Stated explicitly + an invalid_grant branch |
| Creating the logged-in session before verification finishes | Extra cleanup branches needed, easy to forget | Creating sess is the last step |
| Not stating what the access_token is used for | Developers use the access_token to call the Internal API GW | Stated explicitly: after login, the web login access_token is not used anymore |
Part 2: PKCE, state, nonce: three bindings against attacks
1. Why the Authorization Code flow needs "bindings"
In Day 3, Part 1, the flow goes through two redirects via the browser. Each redirect is a moment where the BFF loses control: values in the URL can be injected, altered, or replayed by an attacker. RFC 6749 section 10 and the OAuth Security BCP list three classes of attack corresponding to three gaps:
The three values the BFF generates at /auth/web/login are the three "strings" that tie the legs together so nobody can get in between:
| Value | Binds what to what | Blocks | Checked where |
|---|---|---|---|
code_verifier / code_challenge (PKCE) | code ↔ the client that started the flow | Authorization code interception, code injection | Auth0 checks at /oauth/token |
state | callback ↔ SessionID1 (login:{id}) in the user's browser | CSRF on the callback (login CSRF, session swapping) | BFF checks at the start of the callback |
nonce | id_token ↔ the original /authorize request | id_token replay | BFF checks while verifying the id_token |
All three are stored in login:{id} (SessionID1) and bound to the browser through the cookie login_sid=sid1. That is why Day 2, Part 1 stresses that the login sequence needs a session: without a place to store them, there is nothing to compare against.
2. PKCE: binding the code to the client that started the flow
2.1 The attack to block
The code travels in the redirect URL back to redirect_uri. On mobile, a malicious app can register the same custom scheme; on the web, the code can leak through proxy logs, the Referer, or browser history. If anyone holding the code could exchange it for tokens, the code would be no different from a token.
With a confidential client, the attacker also needs the client_secret. But there is a variant, code injection: the attacker obtains their own code (by logging in with the attacker's account) and injects it into the victim's callback; the victim is logged in to the attacker's account without realizing it, and the attacker can read any data the victim enters afterwards. The client_secret cannot block this because both go through the legitimate BFF. PKCE + state can.
2.2 How it works (RFC 7636)
Only the party holding the original code_verifier can exchange the code. An attacker who intercepts the code and code_challenge (in the URL) gains nothing because SHA-256 is one-way. With code injection: the attacker's code is bound to the attacker's code_challenge, the BFF sends the code_verifier taken from the victim's login:{id} → no match → Auth0 returns invalid_grant.
2.3 Generating it correctly per the spec
RFC 7636 §4.1: code_verifier is a 43–128 character string from the set [A-Z a-z 0-9 - . _ ~]. A simple and correct way: 32 random bytes → base64url → 43 characters.
§4.2: code_challenge = BASE64URL-ENCODE(SHA256(ASCII(code_verifier))), without = padding.
import { randomBytes, createHash } from 'crypto';
/** Secure random string, base64url without padding. 32 bytes → 43 characters. */
export function secureRandomString(bytes = 32): string {
return randomBytes(bytes).toString('base64url'); // Node ≥ 15.7 supports 'base64url'
}
export function generatePkce(): { codeVerifier: string; codeChallenge: string } {
const codeVerifier = secureRandomString(32);
const codeChallenge = createHash('sha256')
.update(codeVerifier, 'ascii')
.digest('base64url'); // padding already removed and +/ replaced with -_
return { codeVerifier, codeChallenge };
}
// Manual equivalent if the runtime does not have 'base64url' yet:
export function toBase64Url(buf: Buffer): string {
return buf.toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
}
The MemberPortal spec has a dedicated "How to generate PKCE" section in the common processes file, stating all three points explicitly: number of bytes, alphabet, padding removed. People writing a new spec often just write "generate PKCE per RFC 7636", and then each developer does it differently (some use hex, some keep the padding); a 64-character hex string is still valid, but it makes cross-team testing harder to reconcile.
2.4 Why a confidential client still uses PKCE
RFC 7636 was written for public clients, but the OAuth 2.0 Security BCP §2.1.1 recommends PKCE for every client, and OAuth 2.1 makes it mandatory. The reasons for a BFF:
- It blocks code injection (section 2.1), which
client_secretcannot. - If part of the flow is later moved to a public client (a native app), the procedure stays the same.
- Cost: one SHA-256 and one field in Redis.
3. state: binding the callback to the browser that started the flow
3.1 The attack to block: CSRF on the callback
The attacker logs in themselves, stops at the step where the code is received (without letting their own browser call the callback), and sends the victim the link https://portal.example.com/auth/web/login-callback?code=<attacker code>&state=<anything>. If the BFF does not check state, the victim clicks it and ends up logged in to the attacker's account (login CSRF / session swapping). Combined with the code injection in section 2.1, this is exactly the scenario that PKCE + state block together.
3.2 How it works
state is a CSPRNG value stored in login:{id}; login:{id} is bound to the browser through the login_sid cookie (HttpOnly). The attacker cannot read the victim's cookie and does not know the victim's state → cannot assemble a valid link.
3.3 Rules in the MemberPortal spec
stateis the first check in the callback, before even looking at whether there is anerroror acode.- Wrong
state→ deletelogin:{id}→ "Login failed". Without deletion an attacker could brute-forcestateagainst the same session (although a 256-bit space makes this theoretically pointless, the "single-use" rule keeps the model simple). - Missing
login_sidcookie orlogin:{id}past its TTL → "Login failed", nothing to delete. - Do not use
stateto carry business data (successUrl,channel...). That data lives inlogin:{id}. Some old guides suggest encodingsuccessUrlintostate; this forces the BFF to sign/encryptstateand opens the door to open redirects if done wrong. With a session in place,stateonly needs to be a random string.
Self-check question: if you drop the
login_sidcookie in leg 1 and instead putsid1intostateitself (state = sid1), what still holds and what breaks?
4. nonce: binding the id_token to the original request
4.1 The attack to block: id_token replay
Suppose the attacker obtains a valid id_token of the victim (from logs, from another client, from an earlier leak). The attacker may try to "slip" that token into their own flow so the BFF believes the person logging in is the victim. With the Authorization Code flow over a server-to-server channel this scenario is much harder than with the Implicit flow, but OIDC Core still requires nonce so that an id_token is valid exactly once, for exactly one session.
4.2 How it works (OIDC Core §3.1.2.1, §3.1.3.7 item 11)
In Day 3, Part 3, nonce is check number 5 of the 7 id_token checks. Wrong → delete login:{id}, "Login failed", like every other verification error.
4.3 nonce vs state, two things that are often confused
state | nonce | |
|---|---|---|
| Layer | OAuth 2.0 | OpenID Connect |
| Where it appears on return | Query string of the callback | Claim inside the id_token |
| Who reads it | BFF, before exchanging the code | BFF, after exchanging the code |
| Binds | Callback ↔ browser session | id_token ↔ authorize request |
| Can they share one value? | Technically yes; MemberPortal generates them separately so each value only appears in one channel (query vs token) |
5. Order of checks at the callback and the "missing binding, resulting hole" table
5.1 Order
Why does state come before error? Because an error response from the IdP must also be a response of this flow. If error were checked first, an attacker could force anyone to see a "Under maintenance" or "Account restricted" screen with just a link, without the correct state. Checking state first turns every fake link into a generic "Login failed".
5.2 Missing binding, resulting hole
| Missing | Exploitation scenario | Severity for a confidential BFF client |
|---|---|---|
| No PKCE | Code injection: the attacker injects their own code into the victim's callback (also requires no state check, or tricking the victim into starting a flow and swapping the code midway through a malicious proxy/extension) | Medium. client_secret blocks plain interception but not injection |
No state | Login CSRF: the victim clicks the attacker's callback link → logged in to the attacker's account; everything the victim enters (payee account numbers, documents) is readable by the attacker | High. This is the most common vulnerability in OIDC audits |
No nonce | Replay an old id_token into a new session; with the code flow it must be combined with a token leak elsewhere | Lower, but OIDC requires the check once it has been sent |
state present but login:{id} not deleted on mismatch | Unlimited retries against the same session sequence | Low, but breaks the single-use rule |
state/nonce/verifier generated with Math.random() | The next value can be guessed after a few samples → a valid callback link can be built | High. As Day 2, Part 1 said: only use a CSPRNG |
state stored in a plain cookie instead of the server session | Attacker sets a cookie from another subdomain (cookie tossing) to force the state | Medium; MemberPortal avoids it by using Redis |
6. How to write this part in the spec
The MemberPortal spec moves shared algorithms into a "common processes" file and endpoints just link to them. Condensed template:
Common: Generate a secure random string
- Use the runtime's CSPRNG (
crypto.randomBytes), 32 bytes, base64url encoded, no padding. Applies to:state,nonce,code_verifier, Session ID, xsrfToken.
Common: Generate PKCE
code_verifierper "Generate a secure random string".code_challenge = BASE64URL(SHA256(ASCII(code_verifier))), strip trailing=, replace+→-,/→_.code_challenge_method = S256.
Endpoint /auth/web/login: data stored in the data store
| Key | Field | Source | Notes |
|---|---|---|---|
login:{sid1} | state | Common: random string | Compared at callback step 2 |
nonce | Common: random string | Compared with the nonce claim (id_token check 5) | |
codeVerifier | Common: PKCE | Sent to /oauth/token | |
successUrl, failureUrl | Query (validated) | Not put into state | |
idProvider | IdP selection (Day 6, Part 3) | auth0 / keycloak | |
channel | Fixed Web | ||
| TTL | SESSION_LOGIN_TTL | Env |
Endpoint /auth/web/login-callback: processing details (first part)
- Get
login:{sid}from thelogin_sidcookie. Missing → go to "Login failed". - Compare the
statequery withlogin:{sid}.state. Different → deletelogin:{sid}, go to "Login failed". - (next: handle
error,code, the token request, verify id_token withnonce...)
Writing it this way lets readers answer "where is value X generated, where is it stored, where is it checked" immediately by looking at a table.
Part 3: id_token is a JWT: 7 checks & JWKS
1. What an id_token is and why the BFF must verify it itself
Day 3, Part 1 ended with the BFF receiving an id_token from /oauth/token. Many people stop here with the argument: "the token arrives over a server-to-server TLS channel from Auth0, with a client_secret, so it must be genuine". OIDC Core §3.1.3.7 still requires that the Client MUST validate the id_token, and so does the MemberPortal spec, because:
- The TLS channel proves "the packet came from the Auth0 server", not "this token is meant for this client, for this session, and is still valid".
- With a backup IdP (Keycloak, Day 6, Part 3), the BFF must be sure the token comes from the same IdP that started the flow.
- Verification is the only place where
nonceis checked (Day 3, Part 2). - If in the future tokens arrive through another channel (a native app uploading a token), the whole verification logic is already in place.
id_token = BASE64URL(header) . BASE64URL(payload) . BASE64URL(signature)
header { "alg": "RS256", "typ": "JWT", "kid": "k2024-09" }
payload { "iss": "https://login.example.com/",
"sub": "auth0|64f1...",
"aud": "<client_id of portal-web>",
"iat": 1726300000, "exp": 1726386400,
"nonce": "Qn3...",
"auth_time": 1726299990,
"https://claims.example.com/account_no": "1234567",
"https://claims.example.com/connection": "Username-Password" }
signature = RSASSA-PKCS1-v1_5(SHA256(header.payload), Auth0's private key)
Readable does not mean trustworthy. The payload is just base64url, anyone can decode it. What makes a token trustworthy is a signature that matches the IdP's public key and claims that match the BFF's expectations. Missing either one is a vulnerability.
2. MemberPortal's seven id_token checks
The MemberPortal spec places this table in the common processes file ("id_token validation") and every callback (web login, step-up, logout callback if needed) links to it. The table is mapped against OIDC Core §3.1.3.7:
| # | Check | What is checked | Source of the expected value | OIDC Core | On failure |
|---|---|---|---|---|---|
| 1 | Signature | Verify the signature with the public key from the IdP's JWKS by kid; alg must be RS256 (allow-list) | JWKS URI of the idProvider in login:{id} | §3.1.3.7 item 6 | Delete login:{id}, "Login failed" |
| 2 | iss | Exactly equals the issuer of the IdP that started the flow | Configuration per idProvider (https://login.example.com/ or the Keycloak issuer) | item 2 | same as above |
| 3 | aud | Contains the client_id of the client in use (portal-web, or the corresponding step-up client) | Env IDP_CLIENT_ID per client | item 3 | same as above |
| 4 | exp | exp > current time (small clock skew allowed, e.g. 60s) | BFF clock | item 9 | same as above |
| 5 | nonce | Equals login:{id}.nonce | SessionID1 | item 11 | same as above |
| 6 | Custom claim connection | https://claims.example.com/connection is in the client's set of valid connections (portal-web: Username-Password, Passkey-Login; step-up clients: the corresponding connection). From it derive usedPasskey = (connection == 'Passkey-Login') | IdP client table | MemberPortal-specific | same as above |
| 7 | auth_time (conditional) | Only when the /authorize request has max_age (step-up sends prompt=login&max_age=600): now - auth_time ≤ 600s. Without max_age the IdP is not required to issue auth_time | Flow configuration | item 13 | same as above |
Three notes for spec writers:
- No check is "optional" once you have sent it: if the flow sends
nonce, you must checknonce; if it sendsmax_age, you must checkauth_time. The MemberPortal spec labels check 7 "conditional", not "optional". - Every verification error goes down the same branch: delete SessionID1, show the "Login failed" screen, do not reveal externally which error occurred (anti-probing), but internal logs have a specific error code for tracing (Day 7, Part 3).
iat,sub,azpare not in the mandatory table, butsubis used (written intosess), and OIDC requiressubto be present; a missingsubmeans the token is invalid. As forazp: OIDC Core §3.1.3.7 items 4–5 recommend (SHOULD) that if the token has anazpclaim it should be checked against theclient_id;jose.jwtVerifydoes not checkazpby itself, so MemberPortal's code adds one more line (skipped only whenaudis single-valued and the IdP does not issueazp, and this must be stated in the spec).
3. Check 1 in depth: JWKS, kid, caching and retry
3.1 What JWKS is
The IdP publishes its set of public keys at .../.well-known/jwks.json (Auth0) or .../protocol/openid-connect/certs (Keycloak). Each key has a kid. The JWT header says which kid signed it; the BFF picks the matching key to verify.
3.2 MemberPortal's rules
- Cache at startup: the BFF loads Auth0's JWKS, and Keycloak's if
ALT_IDP_ENABLED=true, during the boot process (Day 4, Part 1 covers boot). The callback does not have to wait on the network. - Refetch on an unknown
kid: when the IdP rotates keys it adds a newkid. On akidnot in the cache → reload the JWKS once, retrying at most 2 times on 5xx/timeout. Still missing → fail. - Do not trust
algin the header: allow-listRS256. Tokens withalg: noneorHS256are rejected before a key is even touched. This is a classic vulnerability ("alg confusion"): the library readsalgfrom the header, the attacker changes it toHS256and signs with the (public) public key used as the secret. - Do not load JWKS from a URL in the token (
jkuheader). The JWKS URL is fixed configuration peridProvider.
3.3 Sample code with jose
import { createRemoteJWKSet, jwtVerify, JWTPayload } from 'jose';
// Created once at boot per IdP; jose caches and refetches automatically on an unknown kid.
const jwksByProvider = {
auth0: createRemoteJWKSet(new URL('https://login.example.com/.well-known/jwks.json'), {
cooldownDuration: 30_000, // avoid refetch storms
cacheMaxAge: 10 * 60_000, // periodic refresh
}),
keycloak: createRemoteJWKSet(new URL('https://kc.example.internal/realms/acme/protocol/openid-connect/certs')),
};
const issuerByProvider = {
auth0: 'https://login.example.com/',
keycloak: 'https://kc.example.internal/realms/acme',
};
const CLAIM_NS = 'https://claims.example.com/';
const AUTH_TIME_MAX_AGE_SEC = 600;
export interface VerifyContext {
idProvider: 'auth0' | 'keycloak';
clientId: string; // client in use (portal-web, stepup-*)
expectedNonce: string; // login:{id}.nonce
allowedConnections: string[]; // set of valid connections for the client (client table)
maxAgeSec?: number; // did the request have max_age? (step-up: 600)
}
export async function verifyIdToken(idToken: string, ctx: VerifyContext): Promise<JWTPayload> {
// Checks 1-4: signature (kid → JWKS), alg allow-list, iss, aud, exp
const { payload } = await jwtVerify(idToken, jwksByProvider[ctx.idProvider], {
algorithms: ['RS256'],
issuer: issuerByProvider[ctx.idProvider],
audience: ctx.clientId,
clockTolerance: 60,
});
// Check 5: nonce
if (payload.nonce !== ctx.expectedNonce) throw new Error('ID_TOKEN_NONCE_MISMATCH');
// Check 6: custom claim connection is in the client's valid set
const connection = payload[`${CLAIM_NS}connection`] as string | undefined;
if (!connection || !ctx.allowedConnections.includes(connection)) {
throw new Error('ID_TOKEN_CONNECTION_MISMATCH');
}
// Check 7: auth_time, only when the request had max_age (step-up: prompt=login&max_age=600)
if (ctx.maxAgeSec !== undefined) {
const authTime = payload.auth_time as number | undefined;
const now = Math.floor(Date.now() / 1000);
if (typeof authTime !== 'number' || now - authTime > ctx.maxAgeSec) {
throw new Error('ID_TOKEN_AUTH_TIME_TOO_OLD');
}
}
// azp: jose does not check it; OIDC Core §3.1.3.7 (4)-(5)
if (payload.azp !== undefined && payload.azp !== ctx.clientId) {
throw new Error('ID_TOKEN_AZP_MISMATCH');
}
if (typeof payload.sub !== 'string') throw new Error('ID_TOKEN_SUB_MISSING');
return payload;
}
Note for the spec: internal error codes (ID_TOKEN_NONCE_MISMATCH...) only go into logs with bffErrCode; users always see "Login failed".
4. Check 7 in depth: prompt=login and auth_time
4.1 The problem
The IdP keeps its own SSO session (a cookie on the Auth0 domain). If the user logged in to Auth0 30 minutes ago for another ACME app, calling /authorize again will not ask for a password and will return a code immediately. For a normal web login, that is the desired convenience. For step-up authentication (Day 7, Part 1), we need the user to actually re-authenticate right now before withdrawing money; an old SSO session is not enough.
4.2 A two-step solution
- Send
prompt=login&max_age=600to/authorize:prompt=loginasks the IdP to force re-authentication;max_ageforces the IdP to issue theauth_timeclaim in the id_token (OIDC Core §2:auth_timeis only REQUIRED when the request hasmax_age, otherwise OPTIONAL). Withoutmax_age, step 2 has nothing to check. - Do not trust step 1 blindly: check the
auth_timeclaim (the time the user last authenticated, OIDC Core §2) against the current time. MemberPortal chose a threshold of 600 seconds.
Why 600 seconds and not 5 or 60? Because the user may take a few minutes to enter a password, OTP, or passkey; the threshold must be wider than a reasonable interaction time but much narrower than the IdP's SSO session TTL (usually hours). 600s also matches the fixed TTL of the stepup:{id} child session, keeping the time model consistent.
4.3 Why web login does not send prompt
MemberPortal's web login used to send prompt=login too. Then the business requirement changed: customers already logged in to another ACME app should not have to re-enter their password when entering the portal. The spec removed prompt/max_age from the web login endpoint but kept the auth_time check logic in the common process under the condition "only when the request has max_age". Lesson: write common processes by condition, not by endpoint name, so a change in one flow does not break another.
5. Custom claims and the principle "accountNo comes from the id_token"
5.1 Namespaced claims
OIDC Core §5.1.2 recommends that self-defined claims use URL-style names to avoid colliding with standard claims. Auth0 requires a namespace for custom claims in the id_token. MemberPortal uses:
| Claim | Meaning | Who adds it to the token | The BFF uses it to |
|---|---|---|---|
https://claims.example.com/account_no | The customer's account number | Auth0 Action/Rule, read from the custom DB at login | Write sess.accountNo, call the Account Attribute API and the Login Status API |
https://claims.example.com/connection | The connection used to authenticate | Auth0 Action | Check 6 in the verification table: stop tokens from another connection leaking into the flow |
5.2 Why accountNo is not taken from the client
The "easy" way is to have the UI send the account number to /auth/web/login?accountNo=... or have the BFF read it from a cookie. Both are client-controlled: an attacker logs in with their own real account but changes accountNo to someone else's. If the BFF uses that value to call the Core API, the entire authorization model collapses even though authentication is perfect.
Principle: identity and the attributes used for authorization come only from a signature-verified id_token (or from a server-to-server API keyed by the sub in the token). The uid cookie (Day 1, Part 3) is only for UI display; the BFF never reads it to make authorization decisions. This rule repeats in Day 6, Part 1 with the SSO token: sub comes from the SSO Token Verify API, not from the app.
6. Common mistakes and how the spec blocks them
| Mistake | Why it is dangerous | MemberPortal spec |
|---|---|---|
Only jwt.decode() without verify() | Anyone can mint a token with a fake signature | Check 1 is mandatory; the code uses jwtVerify |
No alg allow-list | alg: none / HS256 confusion | States "RS256 only" explicitly |
Not checking aud | A token issued for another client (e.g. stepup-passkey-web) works for web login → step-up checks are bypassed, or vice versa | Check 3, aud per the client in use |
Not checking iss with 2 IdPs | A Keycloak token works in the Auth0 flow and vice versa; a compromised Keycloak drags Auth0 down with it | Check 2, iss per the idProvider in SessionID1 |
| Fetching JWKS on every request | Slow callbacks, IdP rate limiting, an IdP outage takes the BFF down | Cache at boot, refetch by kid |
| Caching JWKS forever | Key rotation makes every login fail | Refetch on an unknown kid + cacheMaxAge |
Trusting auth_time without sending max_age | Without max_age, auth_time is OPTIONAL: it may be missing, or reflect an old SSO authentication | Step-up sends prompt=login&max_age=600; check 7 only applies when max_age is present |
| Taking accountNo from query/cookie | Takeover of another person's account | Only from a verified claim |
| Returning the verification failure reason to the user | Attacker can probe: aud correct, nonce wrong... | One "Login failed" screen, error codes only in logs |
Review Questions
-
In MemberPortal's BFF model, who is the Client per RFC 6749? Why not the browser?
Show answer
The Client is the NestJS BFF. The Client is the party "requesting access on behalf of the Resource Owner" and is registered with the Authorization Server with a
client_id/client_secret. The BFF is the one calling/oauth/token, holding theclient_secret, and receiving theid_token. The browser is only the User-Agent: it carries redirects and thesidcookie, holds no secret, and never sees thecode_verifieror tokens. Naming the roles correctly lets the spec state clearly which party must protect what. -
What is the core difference between a confidential client and a public client? What extra grant type does that give MemberPortal?
Show answer
The difference is the ability to keep
client_secretsecret: a confidential client runs on a server we control (the BFF) and can keep it; a public client (SPA, mobile) cannot because its code runs on the user's device. As a confidential client, the MemberPortal BFF can useclient_credentialsto obtain a Management API token at startup (no user involved), and authenticates itself at/oauth/tokenwith theclient_secret. Public clients do not haveclient_credentialsand must use PKCE. -
List the parameters the BFF attaches to
/authorizeand say which ones the BFF generates itself with a CSPRNG.Show answer
response_type=code,client_id,redirect_uri,scope=openid profile,state,nonce,code_challenge,code_challenge_method=S256,connection(Auth0), optionallyprompt+max_age(step-up). The three values the BFF generates with a CSPRNG on every login:state,nonce,code_verifier(from whichcode_challenge = BASE64URL(SHA256(code_verifier))is computed). All three are stored inlogin:{id}(SessionID1) for comparison at the callback. -
Why does MemberPortal not use
refresh_tokeneven though it is a confidential client?Show answer
Because MemberPortal's "logged-in session" is the Redis session
sess:{id}with TTLSESSION_TTL, not the IdP's access_token. After the callback, the web login access_token is not used to call any Resource Server (the Internal API Gateway trusts the BFF session). With no token to renew there is no need for a refresh_token; keeping one only adds a long-lived secret to protect and another deletion branch at logout. The deliberate exception is step-up MFA (Day 7, Part 1), which keeps an access_token instepup-mfa:{id}with TTL =expires_inbecause that token really does call/mfa/*. -
Why does the spec require that "every error branch in the callback after
login:{id}has been read deleteslogin:{id}"?Show answer
To make the login sequence single-use. If
login:{id}were kept after a wrongstateor wrongcode, an attacker (or a client bug) could make many attempts against the same storedstate/nonce/code_verifier, reducing the value of these bindings. Deleting immediately forces every attempt to start over from/auth/web/loginwith a fresh set of CSPRNG values. The reasonable exception: if there was nologin:{id}to begin with, there is nothing to delete. -
What attack does PKCE block that a confidential client's
client_secretdoes not?Show answer
Authorization code injection. The attacker logs in themselves to obtain their own valid
code, then injects thatcodeinto the victim's callback. Both token exchange requests go through the legitimate BFF with the sameclient_secret, so the secret cannot tell them apart. PKCE binds thecodeto thecode_challengesent by the victim's flow; the BFF uses thecode_verifierfrom the victim'slogin:{id}→ it does not match the attacker's challenge → Auth0 returnsinvalid_grant. (Combined withstate, the attacker cannot even build a valid callback.) -
Why must
code_challengeuseS256and drop the padding? What happens if the padding is kept?Show answer
S256makescode_challengea one-way hash: anyone who intercepts/authorize(with thecode_challenge) still cannot derive thecode_verifier.plainsends the verifier directly, which defeats the purpose. On padding: RFC 7636 defines BASE64URL-ENCODE without=; if the BFF sends a challenge with=while the IdP recomputes it per the standard (no=), the string comparison differs →invalid_granteven though the verifier is correct. This is a common real-world bug when hand-writing base64url, which is why the MemberPortal spec spells out the padding-removal step. -
Why must
statebe checked before looking at theerrorparameter from the IdP?Show answer
Because an error response must also prove it belongs to this browser's flow. If
errorwere handled first, an attacker could just send a linkcallback?error=...&error_description=maintenance::...to force any victim to see an "Under maintenance" or "Account restricted" screen, enabling scams or state probing. Checkingstatefirst turns every invalid link into a generic "Login failed" and deleteslogin:{id}. -
How do
stateandnoncediffer, and why does MemberPortal generate two separate values?Show answer
state(OAuth 2.0) comes back in the callback's query string; the BFF compares it withlogin:{id}.statebefore exchanging the code, preventing CSRF on the callback.nonce(OIDC) comes back inside theid_token; the BFF compares it while verifying the token after exchanging the code, preventing id_token replay. Technically one value could be shared, but MemberPortal generates them separately so each value only appears in one channel: astateleaked through a URL/log does not also leak thenonceinside the token, and vice versa. -
Why does MemberPortal store
successUrlinlogin:{id}instead of encoding it intostate?
Show answer
Putting data into state forces the BFF to sign or encrypt state to prevent tampering; getting one step wrong opens an open redirect (the attacker crafts a state containing their own successUrl). With a Redis session in place, state only needs to be a random string, while successUrl is validated once at /auth/web/login (same BFF domain, well-formed) and stored server-side, where nobody can alter it in transit. General principle: state is a proof, not a vehicle for carrying data.
- The token arrives over TLS from Auth0 with a
client_secret; why must the BFF still verify the signature and claims?
Show answer
TLS only proves that the packet came from the Auth0 server at that moment; it does not prove that the token is meant for this client (aud), for this session (nonce), from the same IdP that started the flow (iss, important with a Keycloak backup), and still valid (exp). Verification is also the only place where nonce and auth_time are checked. In addition, OIDC Core §3.1.3.7 states that the Client MUST validate the id_token; doing it per the standard makes the logic reusable for any channel that delivers tokens later.
- List MemberPortal's 7 id_token checks and say which one is "conditional" and on what condition.
Show answer
(1) Signature by kid from JWKS, alg allow-list RS256; (2) iss matches the IdP per idProvider; (3) aud contains the client_id in use; (4) exp still valid; (5) nonce matches login:{id}.nonce; (6) custom claim https://claims.example.com/connection is in the client's set of valid connections; (7) auth_time: only when the /authorize request had max_age (step-up sends prompt=login&max_age=600), requiring now - auth_time ≤ 600s. Any failed check → delete SessionID1, "Login failed", log an internal error code.
- Why must the BFF allow-list
alg = RS256instead of readingalgfrom the token header?
Show answer
Because the header is controlled by whoever sends the token. If the library trusts the alg in the header: (a) alg: none → an unsigned token is accepted; (b) algorithm confusion: the attacker changes RS256 to HS256 and signs an HMAC using the RSA public key itself (published via JWKS) as the secret; the library uses the public key to verify the HMAC → match. A fixed allow-list of RS256 (and not using jku) eliminates both. jose.jwtVerify with algorithms: ['RS256'] does exactly this.
- Why does MemberPortal's web login not send
prompt=login/max_agewhile the common process still keeps theauth_timecheck?
Show answer
Web login dropped prompt=login because the business wants customers already logged in via SSO to another ACME app not to re-enter their password. But step-up authentication (withdrawals, changing the payee account) still needs forced re-authentication, so it still sends prompt=login&max_age=600. The common process is written by condition ("only when the request has max_age, check auth_time ≤ 600s") rather than by endpoint name, so removing prompt from web login does not affect step-up, and nothing has to be changed in two places.
- Why must accountNo come from the id_token rather than from the query string or the
uidcookie?
Show answer
The query string and cookies are both client-controlled: an attacker logs in with their own account and then changes accountNo to the victim's; if the BFF uses that value to call the Core API, authorization collapses even though authentication is correct. The claim https://claims.example.com/account_no is put into the id_token by Auth0 from the custom DB and is protected by the signature verified in check 1, so it cannot be altered. The uid cookie is only for display; the BFF never reads it to make authorization decisions. By the same principle, Day 6, Part 1 takes sub from the SSO Token Verify API, not from the app.
Hands-on Exercises
Exercise 1: Role-play
For the following three scenarios, fill in a "Resource Owner / Client / AS / RS" table and mark whether the client is confidential or public:
- MemberPortal web login through the BFF.
- The native ACME Trade App calling Auth0 directly (assuming it does not go through the BFF).
- An internal cron job using
portal-managementto call the Auth0 Management API.
Expected output: a 3-row table, each row with all 4 roles and the client type, plus a one-line rationale.
Exercise 2: Build the flow with curl (sandbox)
Create a free Auth0 tenant or a local Keycloak (docker run quay.io/keycloak/keycloak start-dev), and register a confidential client with redirect URI http://localhost:3000/cb. Build the /authorize URL yourself with all the parameters from section 5.1 (generate state, nonce, code_verifier with node -e "console.log(require('crypto').randomBytes(32).toString('base64url'))"), open it in a browser, copy the code from the callback URL, then call /oauth/token with curl.
Expected output: a JSON response containing an id_token; decode the payload with jwt.io or node -e to see the nonce claim matching the value you generated. Record what happens when you call /oauth/token a second time with the same code.
Exercise 3: Condensed spec table
Write an Item/Required/Value table for the POST /oauth/token request in exactly the format of section 6, and list 4 error branches that can occur in leg 3 (for each branch note: retry or not, which session is deleted, which screen is shown).
Expected output: 1 table + 4 error-branch bullets, using MemberPortal's exact session/cookie names.
Exercise 4: Verify PKCE by hand
Run generatePkce() from section 2.3 and print codeVerifier and codeChallenge. Recompute the challenge with a shell command:
printf '%s' "$VERIFIER" | openssl dgst -sha256 -binary | openssl base64 -A | tr '+/' '-_' | tr -d '='
Expected output: two identical strings, 43 characters, no =. Try removing the tr -d '=' step to see the difference.
Exercise 5: Reproduce login CSRF in a sandbox
Use the Keycloak/Auth0 sandbox from Day 3, Part 1. Write a small callback handler (Express/Nest) that deliberately skips the state check. Open two browsers, A (attacker) and B (victim): A logs in, stops at the callback redirect step, and copies the URL; paste the URL into B.
Expected output: B is "logged in" with A's identity. Re-enable the state check (comparing against the value in B's session) and record the result.
Exercise 6: Binding table for a new flow
Suppose a new channel "Desktop app WebView login" is added (to be used in Day 7, Part 3). Fill in a table: value (code_verifier, state, nonce), which endpoint generates it, which Redis key stores it, which step checks it, and the action on mismatch.
Expected output: a 3-row × 5-column table using MemberPortal session/cookie names; point out 1 difference (if any) from the Web channel.
Exercise 7: Verify a real token with jose
Use the id_token from Exercise 2 of Day 3, Part 1. Write a Node script using createRemoteJWKSet + jwtVerify with the correct issuer, audience, algorithms: ['RS256']. Then in turn: use a wrong audience, change 1 character in the payload (re-encode), wait for the token to expire.
Expected output: 3 different error types from jose (JWTClaimValidationFailed, JWSSignatureVerificationFailed, JWTExpired); record the error names and which of the 7 checks each corresponds to.
Exercise 8: Simulate key rotation
With a local Keycloak: create an additional key in the realm (Realm settings → Keys → Providers), give it a higher priority, and log in again to get a token with the new kid. Re-run the script from Exercise 1 with a createRemoteJWKSet created before the key was added.
Expected output: verification still succeeds (jose refetches JWKS on an unknown kid); record the number of requests to the JWKS endpoint from the Keycloak log or a proxy.
Exercise 9: Write the "id_token validation" section for a spec
Rewrite the 7-check table in spec format (columns: Check / What is checked / Where the expected value comes from / Action on failure), adding a "Log error code" column of your own. Then write 3 lines for the case of adding a third IdP: which columns change and which do not. Expected output: a 7-row × 5-column table + a 3-line analysis.
References
- RFC 6749 — The OAuth 2.0 Authorization Framework, §2.1 Client Types, §4.1 Authorization Code Grant
- OpenID Connect Core 1.0, §3.1 Authentication using the Authorization Code Flow
- OAuth 2.0 Security Best Current Practice — RFC 9700
- OAuth 2.0 for Browser-Based Apps (the BFF model)
- Auth0 Docs — Authorization Code Flow
- Auth0 Docs — Confidential and Public Applications
- RFC 7636 — Proof Key for Code Exchange by OAuth Public Clients
- RFC 6749 §10.12 — Cross-Site Request Forgery
- OAuth 2.0 Security Best Current Practice — RFC 9700, §4.5 Authorization Code Injection
- OpenID Connect Core 1.0 §3.1.2.1 (nonce), §15.5.2 Nonce Implementation Notes
- Auth0 Docs — Prevent Attacks and Redirect Users with OAuth 2.0 State Parameters
- Node.js
crypto.randomBytes - OpenID Connect Core 1.0 §3.1.3.7 — ID Token Validation
- OpenID Connect Core 1.0 §2 — ID Token (claims
auth_time,nonce) - RFC 7519 — JSON Web Token (JWT)
- RFC 7517 — JSON Web Key (JWK), JWK Set
- RFC 8725 — JSON Web Token Best Current Practices (alg confusion, allow-list)
- Auth0 Docs — Validate ID Tokens
- Auth0 Docs — Create Custom Claims (namespaced)
jose— createRemoteJWKSet, jwtVerify