OpenID Connect (OIDC): ID Tokens, Sessions, and Identity Federation
From user authentication to ID Token validation, UserInfo, assurance levels, SSO, and federated logout
In-depth edition - study material and professional reference
By João Ricardo Dutra••Complete material
Federated authentication in an enterprise application
Opening Figure - OIDC communicates a verifiable and interoperable authentication event to the client.
Central principle
The proves an authentication event to the client; The access token authorizes access to the resource server.
In-depth edition - study material and professional reference
Chapter presentation
The previous chapter delved into OAuth 2.0 as a delegated authorization framework. OAuth allows a client to obtain limited authority to access a resource server, but does not, by itself, define a standardized way of communicating to the client that a user has been authenticated. OpenID Connect adds this layer of identity by using OAuth endpoints and mechanisms, introducing the openid scope, , standardized claims, , and specific validation rules.
This distinction is decisive in enterprise architectures. The access token is intended for the API; the is intended for the client who initiated the authentication. A web application can validate the and create its own session, while presenting separate access tokens to the API Gateway. Forwarding the to the backend as if it were an API credential mixes up recipients, increases exposure of personal data and creates incorrect validations.
OIDC also organizes issues that go beyond the first login: authentication levels, MFA, step-up, federated identity, claims consent, subject identifiers, metadata , key rotation, distributed sessions and logout. In environments with multiple tenants and providers, security depends on associating each token with the correct issuer and preventing metadata or keys from one domain from being applied to another.
This chapter details the Flow with PKCE from an OIDC perspective, the anatomy and validation of the , , state, , , , , subject identifiers, sessions and logout mechanisms. It also relates concepts to web applications, SPAs, BFFs, native applications, Axway API Gateway, Microsoft Entra and Azure API Management.
How to study this chapter
In each flow, tag four recipients: browser, OIDC client, , and API. Then, associate each artifact with the correct recipient: , , access token, refresh token, session cookie and logout token.
Learning Objectives
Explain why OpenID Connect is an identity layer built on top of OAuth 2.0.
Differentiate , , , Authorization Server and Resource Server.
Describe the Flow with scope openid, state, and PKCE.
Interpret and validate ID Tokens, including , , aud, , exp, iat, , , and .
Distinguish , access token, refresh token, and response.
Understand requested, essential and voluntary identity scopes and claims.
Design public and pairwise identifiers without using email as an immutable key.
Relate , , and to MFA, step-up and risk policies.
Distinguish session on the , session on the client and authorization before APIs.
Compare RP-Initiated, Front-Channel and .
Use and with issuer validation, algorithms and key rotation.
Diagnose OIDC failures in applications, gateways and federated environments.
Chapter structure
17.1 OIDC as an identity layer on top of OAuth 2.0
17.2 Roles, endpoints and artifacts
17.3 The authentication request and the openid scope
17.4 Flow with PKCE
17.5 : purpose, format and claims
17.6 Secure Validation
17.7 state, , PKCE, and at_hash
17.8 Identity claims and scopes
17.9 Endpoint
17.10 Subject identifiers: public and pairwise
17.11 , , , and
17.12 MFA, step-up and authentication context
17.13 Sessions in the OP, in the RP and before APIs
17.14 Logout initiated by RP
17.15 Front-Channel and
17.16 , metadata and
17.17 Client registration and redirect URIs
17.18 Identity federation and chain of trust
17.19 Multi-tenant, multiple issuers and account linking
17.20 Web applications, SPA, BFF and native applications
17.21 OIDC on API Gateways, Axway and Azure
17.22 Threats and hardening
17.23 Troubleshooting
17.24 Case studies and labs
Summary, checklist, exercises, glossary and references
17.1 OIDC as an identity layer on top of OAuth 2.0
OpenID Connect defines an identity layer that allows the client to verify the user's identity based on authentication performed by an Authorization Server that also acts as an . The protocol reuses the authorization endpoint, token endpoint and grants from OAuth 2.0, but adds authentication semantics and a set of messages and validations of its own.
OIDC activation occurs when the request contains the openid scope. Without this value, the transaction remains OAuth and the client should not assume that they will receive an . Other scopes, such as profile, email, address and phone, request standardized sets of claims, but do not replace the openid scope.
The main authentication result is the , a security assertion about the authentication event and the user identifier in the context of that issuer. The client validates this assertion and decides to create or update a local session. The is not a real-time directory lookup and does not guarantee that all attributes remain current throughout the session.
Essential distinction
OAuth answers “what authority was this client given to access a resource?”. OIDC answers “which user was authenticated for this client, by which issuer and under what conditions?”. A system can use both in the same transaction without confusing their tokens.
17.2 Roles, endpoints and artifacts
The is the authenticated person. The , or RP, is the OIDC client that requests and consumes authentication. The , or OP, authenticates the user and issues ID Tokens. On many platforms, the same product plays the roles of OP and Authorization Server, but the conceptual analysis continues to separate authentication for the client and authorization for APIs.
The authorization endpoint interacts with the browser for login, consent, and return to the redirect URI. The token endpoint receives the via back-channel and returns tokens. The Endpoint is a protected resource accessed with an access token. The endpoint publishes metadata, and the jwks_uri references the public keys used in signature verification.
Artifacts have different life cycles. The is short and single-use. The describes authentication for the RP. The access token represents authority before a resource server. The refresh token allows you to obtain new tokens according to policy. Cookies maintain sessions in the OP or RP and should not be treated as equivalent to tokens.
Table 1 - Each artifact has its own recipient and purpose.
Element
Main recipient
Purpose
Authorization code
Token endpoint
Temporarily represent authorization and link front-channel to back-channel.
ID Token
Relying Party
Communicate identity and authentication context to the client.
Access token
Resource Server/API
Authorize protected operations.
Refresh token
Authorization Server
Obtain new tokens without repeating the entire interaction.
UserInfo response
Relying Party
Deliver authorized claims about the user.
OP's cookie
OpenID Provider
Maintain the federated authentication session.
RP cookie
Client application
Maintain the local application session.
Figure 1 - The code passes through the browser, but the tokens are obtained from the token endpoint via a direct channel.
17.3 Authentication request and scope openid
The OIDC request is an OAuth authorization request plus identity requirements. Usual parameters include client_id, response_type, redirect_uri, scope, state, , code_challenge, and code_challenge_method. Other parameters, such as , , login_hint, ui_locales, and acr_values, drive the desired experience or level of authentication, as long as they are supported by the OP.
The redirect_uri must match a previously registered value. Flexible comparisons, broad wildcards, and redirects derived from external headers increase the risk of code bypass and phishing. The client must generate state, and code_verifier with sufficient entropy for each attempt and associate them with the local transaction before redirecting the browser.
The scope parameter must contain openid. Additional scopes indicate groups of claims that the customer requests, but the OP still applies policy, consent and minimization. Requesting profile does not guarantee that all claims in the set will be returned in the ; some may appear in or be omitted.
In the recommended flow, the browser is redirected to the authorization endpoint, the OP authenticates the user and returns an to the client's redirect URI. The client validates state and sends the code to the token endpoint next to the code_verifier. A confidential client also authenticates to the token endpoint using a compatible mechanism, preferably an asymmetric credential or a method appropriate to the environment.
PKCE links the code to the instance that initiated the transaction. The code_challenge was sent in the initial request and the code_verifier is only revealed in the exchange. Even if an attacker intercepts the code, he cannot exchange it without the verifier. PKCE does not replace state or : each value protects a different relationship.
The token endpoint response can contain , access token, token_type, expires_in and, depending on policy, refresh token. The client should not create a session just because it received HTTP 200. First it validates the response, the , the issuer, the audience, the signature, the time window, and other flow requirements.
Figure 2 - The is an assertion intended for the OIDC client, not a universal credential.
17.5 : purpose, format and claims
The is a JWT that contains claims about user authentication. It is signed by the OP and can, in specific scenarios, also be encrypted for the client. The signature provides integrity and authentication of the origin; does not offer confidentiality. Any sensitive claim included in a signed-only JWT can be read by whoever obtains the value.
Fundamental claims include , which identifies the issuer; , which identifies the user locally to the issuer; aud, which identifies the recipient customer; exp and iat, which define validity and issuance. Depending on the flow and request, , , , , , at_hash and appear.
The client must use the and combination as a stable foreign key. Email, telephone and name are changeable attributes and can be recycled. In multi-tenant architectures, the full tenant or issuer also participates in the identity; using just without context can produce collisions between senders.
Even when both are JWTs and share some claims, their recipients and semantics are different. The API must validate the access token issued to its audience; the client validates the issued to its client_id.
Figure 3 - Cryptographic verification is just one step of contextual validation.
17.6 Secure Validation
The customer must compare this with the expected issuer accurately. It then selects a trusted key to verify the signature and restricts algorithms to those that are explicitly accepted. The alg value of the token itself cannot decide the policy alone. The kid assists with key selection, but does not replace trust in the jwks_uri associated with the issuer.
The claim aud must contain the RP's client_id. When there are multiple audiences, identifies the authorized party and must be evaluated according to the protocol rules. exp must be in the future within clock tolerance; iat cannot be absurdly distant; is validated when the request requires maximum authentication age.
If was sent, the token must contain the same value associated with the local attempt. Security claims such as and should only be used when their semantics are documented and trusted by that issuer. The presence of a string similar to “mfa” does not, in itself, create an interoperable level of assurance.
Mature OIDC libraries perform most of the checks, but still require correct configuration of issuer, client_id, algorithms, redirect URIs, and state storage. Decoding the JWT manually and observing claims is not equivalent to validating it.
Table 2 - ID Token acceptance depends on cryptographic and semantic validations.
Verification
Failure avoided
Evidence
exact iss
Accept token from unauthorized issuer
Issuer obtained from trusted configuration.
Signature and alg
Tampered token or improper algorithm
Corresponding JWK and allowlist of algorithms.
aud/azp
Token issued to another client
client_id present and consistent authorized party.
exp/iat/auth_time
Replay outside window or old session
Synchronized clock and limited tolerance.
nonce
Authentication response reuse or replacement
Value per transaction stored on the client.
acr/amr
Accept authentication below requirement
Issuer-defined semantics and local policy.
17.7 state, , PKCE, and at_hash
state ties the authorization response to the client-initiated transaction and helps protect against CSRF and response injection. binds the to the authentication request and reduces token replay. PKCE links the exchange to the instance that produced the code_challenge. The three values can coexist and should not be reused between attempts.
In response types that return artifacts via the authorization endpoint, and at_hash can link, respectively, the and the access token to the . Validation uses part of the hash calculated with an algorithm related to the signature. In a pure code flow, the library may not require both, but the implementer needs to follow the rules of the response type actually used.
Storing these values only in global variables or in localStorage without binding to an attempt allows collisions and attacks by concurrent tabs. The client must maintain a transaction record with issuer, client_id, redirect_uri, state, , code_verifier, time and expected parameters, removing it upon success or expiration.
OIDC defines standardized claims for profile, email, address and telephone number. Scopes such as profile and email are shortcuts for requesting sets of claims. The effective response depends on the OP, consent, policy, and delivery location. A claim can appear in the , the response, or both.
The claims parameter allows you to request claims individually and indicate whether they are essential. “Essential” expresses the customer’s requirement, but does not oblige an incapable OP to manufacture the data; The transaction may fail or proceed as per support and policy. Expected values can also be reported for some claims, requiring care with interoperability.
Minimization is a security and privacy property. The client should request only the necessary attributes and avoid persisting indefinite copies. Group and role claims can grow, vary between directories or represent administrative status; they should not be treated as universal substitutes for object authorization and domain rules.
The Endpoint is a protected resource that returns claims about the user associated with the access token. The client calls this endpoint with a bearer token or sender-constrained mechanism, depending on the profile adopted. The response is typically signed or unsigned JSON, depending on the OP's configuration and metadata.
The client needs to validate that the claim is identical to the . This comparison prevents claims from another user from being associated with the current session. The fact that the connection uses TLS does not eliminate this semantic validation.
is useful when the client needs claims that should not increase the or when the OP applies selective delivery. However, each call adds network dependency and unavailability handling. The design must decide which data is required at login, which can be loaded on demand and how long it can be stored.
Be careful with personal data
ID Tokens and may contain personal data. Do not record complete responses in logs, traces, or error tools. Prefer minimal identifiers, masking, and purpose-aligned retention controls.
17.10 Subject identifiers: public and pairwise
The claim provides a locally unique identifier that is never reassigned within the issuer. In public mode, the same user tends to receive the same for different clients. In pairwise mode, the OP calculates a different identifier per customer sector, reducing the possibility of correlating the user between independent applications.
identifiers are relevant for privacy, but require account linking, support, and migration planning. Two customers from the same sector can share the same as per OP's policy; clients from different sectors receive different values even for the same person.
The application database must persist issuer and as a federated key, maintaining attributes such as email in updateable fields. When there is an issuer migration, tenant merger or subject strategy change, the association needs an explicit procedure and additional proof; it should not be inferred from email coincidence alone.
Table 4 - The subject identifier must balance stability and privacy.
Strategy
Advantage
Operational attention
Public subject
Facilitates correlation between clients of the same issuer.
Increases possibility of tracking between applications.
Pairwise subject
Reduces correlation between client sectors.
Requires sector identifier and linking planning.
Email as key
Sounds simple for business.
It is changeable, can be recycled and is not a secure identifier.
iss + sub
Stable federated identity in the issuer domain.
Needs to be preserved in migrations and multi-tenant.
17.11 , , , and
represents an achieved authentication class or context, according to the vocabulary of the issuer or a profile. lists methods used, such as password, OTP, biometrics or hardware, but the values and combinations need to be interpreted according to the OP's documentation. records when active authentication occurred.
The client can use to require authentication to be no older than a certain threshold. When is requested, becomes essential for verification. controls interaction: none attempts silent authentication; login forces new authentication; consent forces new consent decision; select_account requests account selection, as supported.
acr_values expresses preference for authentication contexts. In high-risk operations, the customer can start a new flow with a stronger requirement. The policy should not rely solely on parameters sent by the front end; the OP and the client need to validate that the returned context satisfies the operation rule.
Table 5 - Claims and parameters describe recency and authentication context.
Claim/parameter
Meaning
Typical usage
acr
Authentication context class achieved
Compare with the level required by the operation.
amr
Methods used in authentication
Issuer-specific auditing and policies.
auth_time
Active authentication instant
Validate max_age and recency.
max_age
Maximum acceptable authentication age
Force reauthentication for sensitive operation.
prompt
Requested interaction behavior
none, login, consent or select account.
17.12 MFA, step-up and authentication context
MFA means using independent factors, not just two steps of the same factor. RP typically does not implement authenticators; it requests or checks a context issued by the OP. For a high-risk operation, the client may initiate step-up and require re-authentication with or equivalent policy.
The decision must consider the authentication already carried out, the current risk, the device, the resource and the time since the last test. A user may have a valid SSO session on the OP, but still need additional authentication to authorize payment, change credentials, or access sensitive data.
The step-up result needs to be linked to the appropriate operation or session. Accepting an old that contained MFA, without evaluating and the transaction context, allows undue reuse. In critical systems, business confirmation may require controls beyond OIDC, such as transactional signature or independent approval.
Assurance principle
Don't treat and as universal strings. Define which values each issuer can issue, what they mean, how they are audited and which operations accept each level. In federations, this mapping needs to be part of the trust agreement.
Figure 4 - SSO, local session and API authorization are related but independent states.
17.13 Sessions in the OP, in the RP and before APIs
The session in OP allows Single Sign-On between clients that trust the same provider. It is usually represented by a cookie under the OP's domain. When another RP sends an authorization request, the OP can reuse the existing authentication, as long as policy, and allow it.
The RP session is created by the application after validating the . In a traditional or BFF web application, an HttpOnly, Secure, and SameSite cookie references state on the server. In pure SPA, libraries can maintain tokens in the browser, which increases the importance of XSS protection and reduces confidentiality guarantees of secrets.
The API normally validates access tokens with each call and does not know the OP's cookie or the RP's cookie. Expiring the local session prevents further actions by the browser, but does not necessarily revoke access tokens already issued. Likewise, revoking a refresh token does not automatically clear all session cookies.
Session design needs to define absolute and inactivity times, renewal, rotation, revocation, reauthentication, and behavior across multiple devices. The “leave everywhere” experience requires inventory and coordination between sessions and tokens.
17.14
In , the client redirects the browser to the OP's logout endpoint. Common parameters include id_token_hint, post_logout_redirect_uri, client_id, and state, depending on provider support and rules. The post_logout_redirect_uri must be previously registered to avoid open redirection.
id_token_hint helps the OP to identify the session and the client, but should not be treated as an access token. state can correlate post-logout return and secure navigation. The RP must clean up its local session regardless of whether the final redirection occurs, preventing a network failure from keeping the user apparently authenticated to the application.
Logout initiated by the RP does not alone guarantee that all other applications connected to the OP are closed. The OP can offer front-channel or back-channel propagation. The product policy needs to make it clear whether “exit” means terminating just the current application, the provider session, or all known sessions.
Conceptual example -
GET /logout?
id_token_hint=eyJ...
&post_logout_redirect_uri=https%3A%2F%2Fportal.example%2Fsigned-out
&state=bG9nb3V0LXRyYW5zYWN0aW9u HTTP/1.1
Host: id.example
Figure 5 - Logout mechanisms differ by channel used and browser dependency.
17.15 Front-Channel and
uses the user agent to load logout URLs from RPs. The mechanism is simple and compatible with web applications, but it depends on the browser, cookies and the completion of navigation. Restrictions on third-party cookies and iframes may reduce reliability in some environments.
sends a direct request from the OP to the endpoint registered by the RP. The body contains a signed logout token, with specific events and identifiers such as or . The RP validates issuer, audience, signature, time, jti and event before invalidating the corresponding session. The endpoint must be idempotent, resilient and not dependent on browser cookies.
Session Management and state polling can also detect changes, but the design should prefer final, ecosystem-supported mechanisms. No logout replaces short token expiration, revocation where applicable, and continued authorization for high-risk operations.
Table 6 - Logout needs to be designed as state propagation, not as a single redirect.
Mechanism
Channel
Strengths
Limitations
RP-Initiated
Browser from RP to OP
Explicit exit experience.
It does not propagate itself to all RPs.
Front-Channel
Browser from OP to RPs
Direct web implementation.
Depends on user agent, cookies and network.
Back-Channel
OP calls RP endpoint
It is not browser dependent; more deterministic.
It requires endpoint, validation and resilient treatment.
Local expiration
RP-controlled
Always available and simple.
Does not log out the OP or other RPs.
17.16 , metadata and
OIDC publishes a configuration document to a well-known address derived from the issuer. The document informs authorization_endpoint, token_endpoint, userinfo_endpoint, jwks_uri, end_session_endpoint when available, response types, scopes, claims, client authentication methods and supported algorithms.
The client must initiate from a previously trusted issuer and verify that the issuer published in the document matches exactly what is expected. You should not accept an issuer freely provided by the user and, from there, fetch metadata without policy, as this allows SSRF, mix-up and trust in unauthorized providers.
jwks_uri publishes public keys. Libraries cache and use kid to select the key. Rotation requires an overlap period: tokens signed with the previous key may still be valid while the new key is already published. On kid failure, the client can update in a controlled manner, avoiding network loops caused by malicious tokens.
reduces manual configuration, but does not make any endpoint trustworthy. The root issuer must come from a validated configuration, allowlist, or federation chain; redirects and jwks_uri remain subject to network and policy restrictions.
17.17 Client registration and redirect URIs
The OP needs to know each client: client_id, application type, redirect URIs, post-logout redirect URIs, authentication methods, keys, scopes and policies. Public clients cannot maintain reliable secrecy; Sensitive customers need to protect credentials and prefer asymmetric authentication when the risk warrants it.
Redirect URIs must be accurate and use HTTPS, except handled exceptions for native app loopback. Custom URI schemes require collision protection and preference for app links or universal links when available. Wildcards and broad prefix matching can allow the to be delivered to an attacker-controlled destination.
Dynamic logging can automate ecosystems, but expands administrative footprint. Software statements, policies, registrant authentication, metadata validation and lifecycle management become necessary. In typical enterprise environments, catalog-and pipeline-governed logging offers greater predictability.
Table 7 - Client classification determines possible controls, not just the application name.
Client type
Credential storage
Recommendation
Web server / BFF
Can protect secret or key on server
Code + PKCE and strong authentication on the token endpoint.
SPA in the browser
Does not have a reliable secret
Code + PKCE; reduce tokens in the browser and evaluate BFF.
Native app
Uses system storage but is public client
Code + PKCE with external browser and secure redirect.
Confidential daemon
Can use key, certificate or workload identity
Client Credentials for APIs; OIDC only when there is a user.
Figure 6 - Federation relies on an explicit chain of metadata, keys, policies, and governance.
17.18 Identity federation and chain of trust
Federation allows an application to trust authentication performed by another domain. In a bilateral relationship, the RP directly configures issuer, metadata, keys and rules. In multilateral federations, entities and trust anchors can publish signed statements and policies that allow the chain of trust to be resolved in a scalable way.
Technical trust does not replace organizational agreement. It is necessary to define onboarding, ownership, assurance, incident response, key rotation, availability, privacy, claims semantics and shutdown. An OP can issue cryptographically valid tokens and still provide attributes that are incompatible with the RP's policy.
OpenID Federation 1.0 formalizes trust chains and metadata policies for ecosystems with many entities. Adoption must consider product maturity, sector profile and real need. In a company with few issuers, explicit configuration may be simpler; In government, financial or healthcare ecosystems, multilateral federation can reduce bilateral agreements.
17.19 Multi-tenant, multiple issuers and account linking
Multi-tenant applications can accept users from multiple directories. Validation needs to determine the authorized issuer for each tenant and prevent a valid key from one tenant from authenticating identities in another. “Common” or equivalent endpoints facilitate initial , but the final token must be associated with the concrete issuer and tenancy policy.
Account linking connects federated identities to a local account. The process must require an already authenticated session and a new proof at the second provider, with protection against CSRF and clear confirmation. Automatically linking accounts because they have the same email allows account takeover when domains or addresses are recycled.
In migrations, preserve the history between old issuer, old and new identity by governed mapping table. Audit logs need to record which federated identity was used, which local account resulted from the link, and who authorized the link.
Multi-emitter rule
Never choose the validation key just for the kid without first fixing the trusted issuer. The same kid can exist on different domains, and metadata from one issuer should not validate tokens from another.
17.20 Web applications, SPA, BFF and native applications
Backend web applications can maintain tokens and credentials on the server and expose only a protected session cookie to the browser. This model reduces the JavaScript exfiltration surface, but requires protection against CSRF, session fixation, cookie theft, and state scalability issues.
SPAs are public clients. with PKCE replaces implicit flow as the modern approach, but tokens remain accessible to the browser context if stored on the front-end. Content Security Policy, dependency reduction, XSS protection, short tokens, and careful storage are required. The BFF standard transfers token handling to the server and offers the browser an origin-restricted session.
Native apps should use external browser or system authentication session, not built-in webview that captures credentials. Redirects use app links, universal links or loopback depending on the platform. PKCE is mandatory in modern practice, and refresh tokens must be rotated and stored in the system's secure mechanism when supported.
Table 8 - The flow is similar, but the execution location changes the threat model.
Architecture
Where are the tokens?
Dominant risk
Web server
Client backend
Session, CSRF, client credential and server access.
SPA
Browser context
XSS, malicious extension and token persistence.
BFF
Backend; browser receives cookie
CSRF, BFF session and backend trust.
Native app
Device storage
Malware, redirect hijacking and compromised device.
17.21 OIDC on API Gateways, Axway and Azure
An API Gateway can act as a to authenticate portal or console users, as an in specific architectures or as a PEP that validates access tokens issued by the same ecosystem. These roles must be configured separately. Validating at an API Gateway does not correct the error of using the wrong token; the API continues to need an access token intended for its audience.
In Axway API Gateway, OIDC filters and services allow you to act as a provider or , create and validate ID Tokens and integrate OAuth flows. The design must separate interactive login policies from API protection policies, maintain governed stores and certificates and validate issuer, audience, and claims according to the role played.
In Microsoft Entra, registered applications receive client_id, redirect URIs, and token settings. Azure API Management typically secures APIs by validating access tokens with validate-jwt or validate-azure-ad-token. The policy can use OpenID configuration to obtain issuer and keys, but must require appropriate audience and claims; simple cryptographic validation does not replace authorization.
In developer portals and administrative consoles, OIDC can provide SSO. For runtime calls, the gateway must preserve user and application identity in a controlled manner, remove equivalent external headers and, when necessary, issue or obtain appropriate credentials for the backend.
Conceptual example - APIM validating API access token
The client application validates the and maintains the user session. The gateway protects APIs by validating access tokens and enforcing policies. Mixing these responsibilities produces wrong audiences and unnecessary exposure of claims.
17.22 Threats and hardening
injection occurs when a code obtained in another transaction is inserted into the client's callback. state, PKCE, , issuer validation and mix-up rules reduce risk. Redirect URI open or flexible registration allows code bypass. XSS can steal tokens in SPAs, while CSRF can trigger callbacks or logout in inappropriate context.
Token substitution occurs when an or access token valid for another client, issuer or purpose is accepted. The defense is strict validation of issuer, audience, , type and context. Unexpected algorithms, keys obtained from the URL indicated by the token and global kid cache create cryptographic and multi-issuer flaws.
Login CSRF associates the victim's session with the attacker's account, causing the victim to operate under the wrong identity. State per transaction, session correlation and account confirmation reduce risk. Automatic account linking via email is another form of mistaken identity.
Logout also has threats: open redirection, partial wipe, logout token replay, and session denial. post_logout_redirect_uri must be registered; logout tokens need signature, audience, events, jti and time; Endpoints must be idempotent and limit abuse.
Table 9 - Secure OIDC depends on links between transactions, issuers, clients and artifacts.
Threat
Implementation error
Main control
Issuer mix-up
Process a response without fixing the expected OP
Per-transaction issuer, reliable metadata, and exact validation.
Code injection
Accept a code not bound to the attempt
PKCE, state, nonce and correlated callback.
Token substitution
Accept JWT from another audience or type
aud, azp, typ, issuer and purpose of the token.
Login CSRF
Create session with non-user initiated response
Strong state and transaction record.
XSS in SPA
Tokens accessible to compromised script
BFF, CSP, script reduction and short token.
Improper account linking
Link by matching email
Reauthentication with both identities and explicit confirmation.
Logout replay
Accept repeated or old logout token
jti, exp/iat, signature and idempotence.
17.23 Evidence-driven troubleshooting
The diagnosis must separate front-channel, token endpoint, validation, session creation and API access. An error in the callback could be a divergent state, incorrect redirect URI or expired code. An error in the token endpoint could be client authentication, PKCE, code reuse or clock. A successful login followed by a 401 on the API usually points to a missing access token, wrong audience, or gateway policy.
Collect correlation ID, expected issuer, client_id, normalized redirect URI, response_type, scopes, timestamps, kid, algorithm, audiences and result of each validation. Never register full tokens, authorization codes, code_verifiers, secrets or cookies. For analysis, use synthetic claims or controlled irreversible hashes.
Intermittent issues after key rotation may indicate caching, nodes with divergent clocks, or no overlap. Failures in only one tenant suggest issuer, consent, claims or tenancy policy. Logout that works in one application and not in another must be analyzed by channel type, / , registered endpoint and local state of the RP.
Table 10 - Symptoms must be associated with the exact stage of the flow.
state issued and received, with a correlated session.
invalid_grant in token endpoint
Expired/reused code, redirect or divergent verifier
Time, redirect_uri, and verifier hash.
Invalid signature
new kid, wrong issuer, JWKS cache
Metadata, current JWKS and clock.
Invalid audience
ID Token issued to another client_id
aud, azp and client_id configured.
invalid_nonce
Response from another attempt or replay
nonce stored per transaction.
Login works, API returns 401
Access token missing, expired or wrong audience
Authorization header and gateway policy.
Partial logout
Mechanism not propagated or RP did not clear session
sid/sub, endpoint and logout logs.
Telemetry checklist without credentials exposure
Secure diagnostic logging:
- transaction_id and correlation_id
- expected issuer and client_id
- normalized redirect_uri
- state_match, nonce_match, and pkce_result
- alg, kid, aud, azp, and timestamps without the raw token
- session created, renewed, or invalidated
- OP error code and responding stage
17.24 Case studies
Case 1 - accepted by the API
A portal sends the in the Authorization header to the API Gateway. The token has a valid signature and aud equal to the portal's client_id, not the API. The gateway is configured to only check signature and expiration, so it accepts the call. The backend starts to trust a token destined for another component and without resource scopes.
The fix is to request an access token for the API audience, validate issuer, audience, type and scopes on the gateway and keep the only on the client. The migration should look at existing consumers and prevent both types from being accepted indefinitely.
Case 2 - Intermittent failure after key rotation
The OP starts signing new tokens with another kid, but an application node keeps in cache for an excessive period of time. Some users receive tokens with the new key and fail; others continue to authenticate with old tokens. Restarting the node seems to fix it temporarily.
The diagnosis compares kid, serving node and cache age. The solution includes cache with controlled refresh on unknown kid, key override by issuer, observability and updated OIDC library. You should not fetch the key URL provided by the token.
Case 3 - Account takeover by automatic linking
An application automatically links a new federated identity to the local account when the email matches. A domain releases an old address, which is assigned to someone else. The new owner authenticates with the OP and receives access to the historical account.
The fix requires + as identity, explicit linking process with reauthentication and confirmation, user alerts, and audit trail. E-mail remains a contact attribute, not proof of identity continuity.
Case 4 - Logout closes the portal, but does not close other applications
The portal clears its cookie and calls the OP's logout endpoint, but another RP keeps the local session active. The “global logout” expectation was not documented and the OP did not send front-channel or .
The design is revised to register back-channel endpoints, issue , validate logout tokens and define unavailability behavior. The interface now distinguishes “exit this application” from “close corporate session”.
Observation labs
Lab 1 - complete OIDC flow
Use an authorized laboratory provider and client.
Capture the authorization request without recording real credentials.
Identify state, , code_challenge, code and token response.
Validate the with library and compare , aud, and time.
Lab 2 - validation matrix
Create synthetic tokens or fixtures signed with a lab key.
Wrong issuer test, wrong audience, expiration, divergent and something not allowed.
Record which validation rejected each token.
Confirm that the client does not create session after any failure.
Lab 3 - and minimization
Request openid, profile and email in a test environment.
Compare and claims.
Validate that is the same in both answers.
Reduce scopes and observe which data is not delivered.
Lab 4 - session and logout
Create two lab RPs under the same OP.
Observe SSO and differentiate cookies from OP and RPs.
Test local logout, RP-Initiated and, if supported, back-channel.
Record which sessions remain active in each scenario.
Lab 5 - rotation
Publish two lab keys and change the active key.
Note cache, kid, and acceptance of old tokens.
Controlled refresh test on unknown kid.
Set overlay window and crash alerts.
Chapter summary
OpenID Connect adds interoperable authentication to OAuth 2.0. The openid scope activates the protocol, and the communicates an authentication event to the . The access token continues to be used for the API. Confusing the two artifacts is an architectural flaw, even though they are both JWTs.
Flow with PKCE uses state, and code_verifier to protect different relationships. The client validates issuer, signature, algorithm, audience, , time, and assurance requirements before creating session. Claims like , and are only useful when their semantics are known.
delivers authorized claims and must maintain the same . The federated identity must be persisted by + ; Email is not an immutable key. Public and pairwise subjects offer different correlation and privacy properties.
OP session, RP session and API tokens are independent states. Logout requires explicit policy and can use RP-Initiated, Front-Channel or Back-Channel. and make configuration and rotation easier, but the root issuer and chain of trust need to be controlled.
In gateways, OIDC protects portal and application logins, while APIs typically require access tokens. Axway and Azure offer resources for and validation, but configuration of audience, claims and authorization remains the responsibility of the architecture.
Next step of the course
Chapter 18 will delve deeper into JWT, JWS, JWE, and JOSE: serialization, algorithms, key identifiers, , rotation, validation, token encryption, and implementation pitfalls.
OpenID Connect Checklist
The openid scope is only present in OIDC authentication flows.
The client uses with PKCE and exact redirect URI.
state, and code_verifier are unique per transaction and removed after use.
The issuer is configured or resolved by authorized chain of trust.
The signature is validated with the allowed algorithm and correct key.
aud and are compared to the expected client_id.
exp, iat and use synchronized clock and limited tolerance.
The remains on the client and does not replace the API access token.
is compared to the .
The federated account uses + , not email, as the foreign key.
and have semantics documented by issuer.
OP and RP cookies have protection, expiration and renewal policy.
Local logout, RP-Initiated, front-channel and back-channel have defined behavior.
and have cache, controlled refresh and network protection.
Multi-tenant validates concrete issuer and tenancy policy.
Logs do not store tokens, codes, secrets, verifiers or cookies.
OIDC libraries are kept up to date and tested with negative cases.
Exercises
Explain why OAuth 2.0 is not, in isolation, a login protocol.
Differentiate OP, RP, Authorization Server and Resource Server.
Describe the role of scope openid, state, and PKCE.
List the mandatory validations of an .
Explain when needs to be analyzed.
Compare , access token and response.
Explain why + is better than email for account linking.
Compare public and identifiers.
Model step-up using , and .
Differentiate session in OP, session in RP and access token validity.
Compare RP-Initiated, Front-Channel and .
Describe how to handle rotation without restarting applications.
Propose a multi-tenant policy that avoids issuer mix-up.
Explain why the gateway must validate access token, not .
Create a troubleshooting script for invalid_state and invalid_grant.
Glossary
Table 11 - Essential vocabulary of the chapter.
Term
Definition
acr
Authentication Context Class Reference; authentication context class.
amr
Authentication Methods References; methods used in authentication.
auth_time
Time at which active user authentication occurred.
Authorization Code
Short artifact exchanged on token endpoint.
azp
Authorized Party; authorized client when aud contains multiple values.
Back-Channel Logout
Direct logout from the OP to the RP endpoint.
c_hash
Hash that links authorization code to the ID Token in applicable flows.
Discovery
Mechanism for obtaining metadata from the OpenID Provider.
End-User
Person authenticated by the OpenID Provider.
Front-Channel Logout
Logout propagated by the browser between OP and RPs.
ID Token
JWT intended for the RP to communicate the authentication event.
iss
Issuer; token issuer identifier.
JWKS
JSON set of public keys for cryptographic validation.
max_age
Maximum acceptable authentication age.
nonce
Value that links authentication request and ID Token.
OpenID Provider
Entity that authenticates the user and issues ID Tokens.
Pairwise subject
different sub by customer sector to reduce correlation.
prompt
Parameter that controls interaction such as none, login or consent.
Public subject
sub reused between clients according to issuer policy.
Relying Party
OIDC client that trusts OP authentication.
RP-Initiated Logout
Client-initiated logout request.
sid
Session identifier used in logout mechanisms.
sub
Subject Identifier; user identifier in the issuer.
UserInfo
Protected endpoint that returns authorized claims from the user.
Annex A - OIDC Architecture Matrix
Table 12 - The choice depends on the platform, risk, experience and capacity of the provider.
Scenario
Initial architecture
Essential controls
Corporate web application
Code + PKCE with server-side session
client authentication, secure cookie, CSRF, nonce and logout.
Low-risk SPA
Code + PKCE
CSP, short token, no secret and XSS protection.
Higher-risk SPA
BFF + Code + PKCE
tokens in the backend, HttpOnly cookie and CSRF.
Native app
Code + PKCE with external browser
app/universal link, secure storage and refresh rotation.
Multi-tenant portal
Issuer by tenant and explicit policy
aud/azp, tenancy, consent and secure account linking.
Step-up operation
New authorization request with assurance
max_age, acr, auth_time and link to operation.
SSO with corporate logout
OP session + RP-Initiated + back-channel
sid, logout token, idempotence and observability.
multilateral federation
OpenID Federation or sector profile
trust anchors, metadata policies and governance.
Technical references
OpenID Foundation. OpenID Connect Core 1.0 incorporating errata set 2.
OpenID Foundation. OpenID Connect 1.0 incorporating errata set 2.
OpenID Foundation. OpenID Connect 1.0. 2022.
OpenID Foundation. OpenID Connect 1.0. 2022.
OpenID Foundation. OpenID Connect 1.0, with errata incorporated. 2023.
OIDC is an evolving set of specifications and profiles. Before deploying , logout, federation, or assurance claims, confirm the version supported by the provider, library, and gateway. Internet-Drafts and proprietary extensions do not automatically replace final specifications.