OAuth 2.0 in Depth: Flows, Tokens, and Security
Back to Learn
FAACChapter 16

Corporate API Fundamentals and Architecture

OAuth 2.0 in Depth: Flows, Tokens, and Security

Roles, endpoints, Authorization Code with PKCE, Client Credentials, refresh tokens, introspection, revocation, and modern protection practices

In-depth edition - study material and professional reference

OAuth 2.0 flows protected by PKCE, tokens, and modern security controls

OAuth 2.0 delegation: authorization without sharing the user's password

OAuth 2.0 delegating authority between user, client, authorization server, gateway and API
Opening Figure - OAuth delegates limited authority without making the the owner of the user's credentials.

Central principle

The is granted limited authority to access an API; User authentication and API authorization remain separate decisions.

In-depth edition - study material and professional reference

Chapter presentation

Previous chapters separated identity, authentication, authorization, and static credentials. Now the course delves into the OAuth 2.0 framework, created to allow a to obtain limited authority to access a protected resource. The central idea is to replace the direct sharing of credentials with temporary artifacts, with controlled audience, , duration and context.

OAuth 2.0 is not a single, closed protocol. It is a family of roles, endpoints, grants, types, token formats, and extensions. The security of a deployment depends on the correct composition of these elements. An flow can be robust when it uses , strict redirect URI, and protection, but it can be vulnerable when it accepts broad redirects, mixes issuers, or exposes codes and tokens in logs.

The original specification remains important, but modern practice is also guided by later documents. Security Best Current Practice consolidates operational experiences, advises against insecure modes and reinforces , exact URI redirect, mix-up protection, restriction and replay defense. Extensions such as , , RAR, mTLS, , resource metadata and address higher risk scenarios and corporate integrations.

This chapter goes through the complete cycle: registration, authorization request, token issuance and use, renewal, revocation, , delegation between services and enforcement in API Gateway. The goal is to allow the reader to design and diagnose real flows without confusing user authentication, authentication, consent, resource authorization, and token validation.

Specification status

OAuth 2.1 remains an Internet-Draft in 2026. It consolidates modern practices, but does not automatically replace published RFCs. For regulatory decisions, use current RFCs and OAuth 2.0 Security Best Current Practice, checking the current draft version for additional guidance only.

Learning Objectives

  • Explain the delegation problem solved by OAuth 2.0 and its limits.
  • Distinguish , , and .
  • Differentiate authorization endpoint, token endpoint, , revocation and metadata.
  • Sort public and confidential clients and choose authentication compatible with their ability to protect keys.
  • Describe with and the , nonce, issuer and redirect URI controls.
  • Apply , Device Authorization and refresh tokens in appropriate scenarios.
  • Distinguish grants, codes, access tokens, refresh tokens and ID tokens.
  • Design scopes, audiences, resource indicators, consent and detailed authorization.
  • Understand opaque tokens, JWTs, , revocation, and profiles.
  • Apply , , , RAR, mTLS, and according to risk.
  • Integrate OAuth with API Gateways, Axway API Gateway and Azure API Management.
  • Diagnose invalid_request, invalid_client, invalid_grant, invalid_token and insufficient_scope.

Chapter structure

  • 16.1 The problem that OAuth 2.0 solves
  • 16.2 Roles and trust boundaries
  • 16.3 Endpoints, metadata and channels
  • 16.4 Registration, types and redirect URIs
  • 16.5 Grants, flows and token types
  • 16.6 in depth
  • 16.7 and interception protection
  • 16.8 , nonce, issuer and mix-up protection
  • 16.9 authentication
  • 16.10 Web applications, SPAs, native apps, and BFF
  • 16.11
  • 16.12 Device Authorization
  • 16.13 Refresh tokens, rotation and reuse
  • 16.14 Access tokens, scopes, audience and resource indicators
  • 16.15 Opaque tokens, and revocation
  • 16.16 JWT access tokens and validation
  • 16.17 Consent, least privilege and Rich Authorization Requests
  • 16.18 , and
  • 16.19 Sender-constrained tokens with mTLS and
  • 16.20 and on-behalf-of
  • 16.21 Metadata of the and protected resource
  • 16.22 OAuth on API Gateways, Axway and Azure
  • 16.23 Threats and hardening
  • 16.24 Evidence-driven troubleshooting
  • 16.25 Case studies and labs
  • Summary, checklist, exercises, glossary and references

16.1 The problem that OAuth 2.0 solves

Before delegation frameworks, it was common for an application to ask for a user's password to access another system. This practice gave the excessive power, prevented limiting operations, made selective revocation difficult and exposed reusable credentials. If the were compromised, the attacker could act as the user on any interface that accepted the same password.

OAuth replaces this sharing with a of authority. The requests authorization for a purpose; The authenticates the user when necessary, applies policies and issues an destined for the . The receives only the capability represented by the token, not the user's primary credential.

The framework does not alone define how the user authenticates, how the API models object permissions or how the token must be formatted. It also does not transform an into proof of login for the . OpenID Connect meets the need to communicate user authentication to the , while the API remains responsible for fine-grained authorization and business rules.

Mental model

OAuth answers: “how does a obtain and present limited authority for a resource?” It does not answer itself: “who is the user for the interface?”, “does the user own this object?” or “is this transaction allowed by the domain?”.

OAuth roles and their communication and trust channels
Figure 1 - Roles are logical responsibilities; a product can implement more than one role, but the boundaries must remain explicit.

16.2 Roles and trust boundaries

The is the entity capable of granting access to the resource. In many flows it is a person, but it can also be an organization or administrative policy. The is the application that requests access. He does not automatically own the data and should not be given more authority than is necessary for his role.

The authenticates the when applicable, evaluates the request, records consent or policy, and issues tokens. The is the API that accepts access tokens and decides whether the operation is allowed. On an enterprise platform, the API Gateway can act as part of the by validating the token and applying cross-cutting controls, while the backend retains domain decisions.

Logical roles do not necessarily equate to separate processes. The same product can host authorization and resources, and a gateway can intermediate multiple APIs. Even so, issuer, audience, keys, endpoints and responsibilities must be distinct to prevent a token issued for one service from being improperly accepted by another.

Table 1 - Each role has its own controls and evidence.
PaperMain responsibilityCommon drawing error
Resource ownergrants authority over resourcestreat consent as unrestricted authorization.
Clientrequest and use tokensstore secret in application unable to protect it.
Authorization serverissues tokens and publishes metadataissue wide audience and accept flexible redirect URI.
Resource servervalidates token and authorizes operationaccept JWT only because the signature is valid.

16.3 Endpoints, metadata and channels

The authorization endpoint receives requests through the user agent and conducts interaction with the . The token endpoint is accessed directly by the to exchange grants for tokens. This separation creates two channels: front-channel, exposed to browser, history, extensions and redirects; and back-channel, protected by TLS and used for direct requests between and .

Optional endpoints expand operation and interoperability. allows the to query the of a token. Revocation allows you to invalidate refresh tokens and, depending on the implementation, access tokens. receives authorization parameters in advance via back-channel. Metadata describes issuer, endpoints, authentication methods, algorithms and supported capabilities.

Endpoint URLs are security data. The must not construct them by concatenation or accept metadata from an untrusted source. The returned issuer must match the configured issuer. TLS, hostname validation, and reliable DNS resolution remain essential because OAuth protects authority, not replaces channel security.

Table 2 - Endpoints have different exposures and controls.
EndpointTypical channelPurpose
Authorizationfront-channeluser interaction and authorization code issuance.
Tokenback-channelgrant exchange and client authentication.
Introspectionback-channelactivity query and token attributes.
Revocationback-channeltoken invalidation as per policy.
PARback-channelprotected registration of authorization parameters.
Metadatasource-authenticated readdiscovery of endpoints and capabilities.

16.4 Registration, types and redirect URIs

The registry associates client_id, redirect URIs, application type, contacts, keys, authentication methods and allowed grants. The client_id is a public identifier, not a secret. Security depends on the correct link between the identifier and registered properties, especially redirect URIs and cryptographic material.

Sensitive clients can keep credentials under control, such as backend web applications or services. Public clients run in environments where the user or attacker can extract the software and its values, such as SPAs and native applications. Inserting client_secret into a JavaScript, mobile package, or distributed application does not make the ; the secret becomes copiable.

Redirect URI must be compared by exact match, except for very specific rules for native application loopback. Wildcards, prefix matching and open redirectors allow bypassing codes. Each environment must have its own URIs, and the application must validate the return route before starting any local session.

secrecy

A value embedded in a SPA, mobile application, or distributed binary must be considered public. Adequate protection comes from , strict redirect URI, operating system, BFF when applicable, and token restriction - not from trying to hide a client_secret.

16.5 Grants, flows and token types

is the representation of an authorization used by the to obtain an . , , and device code are examples. “Flow” describes the complete sequence of interactions. Confusing with token leads to inaccurate logs and policies: the is short, single-use and intended for the token endpoint; the is presented to the API.

The represents authority for a . The allows you to request new access tokens and must be restricted to the . The ID token belongs to OpenID Connect and communicates facts about authentication to the ; should not be used as an . Each artifact has a different recipient, useful life and protection.

Old Implicit and Password Credentials should not be chosen for new projects. The first exposes tokens on the front-channel and has lost its justification with ; the second delivers user credentials to the and prevents many modern controls. Migrations should prioritize with or appropriate machine-to-machine flows.

Table 3 - Artifacts are not interchangeable.
ArtifactRecipientOperating property
Authorization codetoken endpointshort, single-use, and client-bound/redirect URI/PKCE.
Access tokenresource servertemporary authority, audience and scope.
Refresh tokenauthorization serverrelative long-term credential; requires protection and rotation.
ID tokenOIDC clientassertion about authentication, not generic API credential.
device_codetoken endpointcontrolled polling for limited device.
Authorization Code with PKCE using front-channel and back-channel
Figure 2 - links the exchange of the to a proof created by the customer.

16.6 in depth

The creates an authorization request containing response_type=code, client_id, redirect_uri, , and parameters. The browser is redirected to the , where the user can be authenticated and the policy evaluated. If successful, the returns an for the registered redirect URI.

The receives the code and exchanges it in the token endpoint. This direct request includes grant_type=authorization_code, code, redirect_uri, and code_verifier. Confidential clients also authenticate themselves. The server checks one-time usage, term, , redirect URI and before issuing tokens.

The code must not carry reusable authority or be sent to APIs. It exists to reduce token exposure in the front-channel and allow validations in the back-channel. Logs, analytics tools, error pages and referrers should not record the value. After the switch, the application must remove sensitive parameters from the URL and establish its own session in a secure way.

Authorization request - illustrative values

GET /authorize?response_type=code
  &client_id=payments-portal
  &redirect_uri=https%3A%2F%2Fapp.example%2Fcallback
  &scope=payments.read%20payments.write
  &state=valor-aleatorio
  &code_challenge=base64url-sha256-verifier
  &code_challenge_method=S256

Exchange of code for tokens

POST /token
Content-Type: application/x-www-form-urlencoded
grant_type=authorization_code
&code=AUTHORIZATION_CODE
&redirect_uri=https%3A%2F%2Fapp.example%2Fcallback
&client_id=payments-portal
&code_verifier=INSTANCE_RANDOM_SECRET

16.7 and interception protection

starts with a random, high-entropy, and trial-unique code_verifier. The calculates code_challenge = BASE64URL(SHA256(code_verifier)) and sends the challenge to the authorization endpoint. When changing the code, it displays the original verifier. The recalculates the challenge and requires matching.

If an attacker intercepts the , he will not be able to exchange it without the verifier. Method S256 must be used; plain exists for restricted compatibility and does not offer the same protection against observation as challenge. does not replace , exact redirect URI, TLS, or authentication. It solves a specific threat: interception and injection.

must also be required for confidential clients when using . In addition to standardizing the flow, it protects against attacks in which code obtained in another context is injected into the session. The verifier must not be reused and must be associated with the same transaction that contains and redirect URI.

Table 4 - PKCE is a per-transaction proof, not a permanent credential.
ElementWhere does it appearRequirement
code_verifiertoken requestrandom, secret during the transaction and not reused.
code_challengeauthorization requestderived from verifier by S256.
code_challenge_methodauthorization requestS256 for new systems.
Bondclient statussame attempt, client_id, redirect URI and code.

16.8 , nonce, issuer and mix-up protection

ties the authorization response to the session that initiated the request and helps prevent CSRF. It must be unpredictable, single-use and locally associated with the issuer, redirect URI, and user intent. Treating only as a signed return URL may leave the session without adequate protection against unsolicited responses.

Nonce belongs to OpenID Connect and links the ID token to the authentication request. It does not replace in securing the OAuth flow. On clients using OIDC, both may be required: protects the redirect and nonce is validated within the ID token.

mix-up attacks exploit clients that talk to multiple issuers and do not link the response to the correct issuer. The must use trusted metadata, validate the iss parameter when supported, and send the code only to the issuer token endpoint associated with the transaction. Never select the token endpoint based on unvalidated response data.

Minimum transactional

Store, tentatively: expected issuer, client_id, redirect URI, , code_verifier, nonce when there is OIDC, requested scopes and time. Consume the record once and expire quickly.

16.9 authentication

The token endpoint needs to distinguish the presenting the . client_secret_basic is simple, but relies on symmetric secret and secure transport. client_secret_post puts the secret in the body and increases log risk; should be avoided when the Basic method is supported. Secrets need vault storage, rotation, ownership, and per environment.

private_key_jwt uses a JWT assertion signed by the 's private key. The validates issuer/subject, audience, expiration, unique identifier and signature. The private key is not sent, and rotation can be managed by JWKS. The mechanism requires jti replay prevention and strict audience validation of the token endpoint.

mTLS authentication links authentication to the certificate presented in the TLS connection. Can use traditional PKI or registered certificate. In environments with proxies, it must be clear where TLS ends and how the identity of the certificate is preserved. Strong authentication does not eliminate the need for in the .

Table 5 - The method must correspond to the customer's actual capacity.
MethodMaterialAdvantageCaution
client_secret_basicsymmetric secretbroad supportrotation, logs and sharing.
private_key_jwtprivate keydoes not send secrets; good automationjti, audience and JWKS rotation.
mTLS client authenticationcertificate and keystrong connection to the channelTLS termination and certificate cycling.
noneno authenticationsuitable for public customersrequire PKCE and secure redirect URI.

16.10 Web applications, SPAs, native apps, and BFF

Traditional web applications maintain code and credentials on the server. The browser only receives a protected session cookie, while the backend runs , stores tokens and calls APIs. This separation reduces exposure of tokens to JavaScript, but requires protection against CSRF, fixation, XSS and session theft.

SPAs are public clients. with is the modern flow, but access tokens stored in the browser are still exposed to XSS and extensions. A Backend for Frontend can receive the code, maintain tokens on the server and expose only HttpOnly, Secure and SameSite cookies to the browser. BFF adds and infrastructure but reduces the token footprint.

Native applications use external browsers and redirect URIs based on app links, universal links, custom schemes or loopback. Embedded webviews degrade security and SSO experience. The system must prevent another application from capturing the redirect URI and always combine the return mechanism with .

Table 6 - The architecture changes where the token is exposed.
TypeClassificationPreferred StorageFlow
Web with backendconfidentialtokens on the server; browser session cookieAuthorization Code + PKCE.
pure SPApublicmemory when possible; minimize persistenceAuthorization Code + PKCE.
SPA with BFFConfidential BFFtokens on BFF; protected cookieAuthorization Code + PKCE.
Native Apppublicsecure system storageAuthorization Code + PKCE and external browser.

16.11

are used when the acts on its own behalf, without a human in the transaction. The authenticates to the token endpoint and receives an associated with the application identity. It is suitable for services, jobs and automations that have their own permissions.

should not be used to simulate users or transport arbitrary user_id. Authorization must be based on the application principal, its tenant, owner, and application permissions. If one service needs to preserve user context when calling another, on-behalf-of or is more suitable.

Because the token can open broad access, static credentials should be replaced with private_key_jwt, mTLS, managed identity, or workload federation when possible. Application scopes need to be separated from delegated scopes to prevent an app-only token from being confused with user authority.

- conceptual example

POST /token
Authorization: Basic base64(client_id:client_secret)
Content-Type: application/x-www-form-urlencoded
grant_type=client_credentials
&scope=settlements.process

Review question

If the operation needs to know “which user authorized?”, alone do not provide that answer. The main thing is the application.

16.12 Device Authorization

The Device Authorization supports devices with limited input or without a convenient browser. The requests and user_code, presents the user with a verification_uri, and starts polling the token endpoint. The user completes authentication and authorization on another browser-capable device.

The must respect interval, expires_in and errors such as authorization_pending and slow_down. Aggressive polling creates load and can cause blocking. The user_code needs to be short enough to type, but protected by rate limiting, expiration, and binding to high-entropy .

The flow should not be used as a shortcut for applications that already have a suitable browser. The interface must clearly show which device and operation is being authorized, reducing phishing attacks in which a code sent by a third party is entered by the victim.

Table 7 - The flow separates the requesting device from the authentication channel.
StepArtifactControl
Homedevice_code + user_codesecret device_code; short and expirable user_code.
Interactionverification_uridisplay customer context and prevent phishing.
Pollingdevice_coderespect interval and slow_down.
Conclusionaccess/refresh tokenbind to customer and approved policy.
Lifecycle of grants, access tokens and refresh tokens
Figure 3 - Tokens have different life cycles and revocation decisions.

16.13 Refresh tokens, rotation and reuse

is a high-value credential because it allows you to obtain new access tokens without repeating the entire interaction. It should only be sent to the token endpoint, protected in suitable storage and limited to the and the original authorization. Short access tokens reduce exposure; refresh tokens maintain controlled continuity.

For public customers, BCP recommends sender-constrained or rotated refresh tokens. In rotation, each use produces a new and invalidates the previous one. If an old token reappears, the server detects possible theft and revokes the corresponding family or authorization. The implementation needs to handle concurrency and missed responses without creating false positives.

Absolute expiration, expiration due to inactivity, revocation due to logout, password change, withdrawal of consent and risk must be defined. “ never expires” transfers all control to perfect revocation, something difficult in distributed systems. The should treat invalid_grant as a need for reauthorization, not as a reason to repeat indefinitely.

Table 8 - Refresh token needs its own policy.
ControlObjectiveOperational decision
Rotationdetect reuserevoke family and log incident when old token reappears.
Sender constraintbind to a keyvalidate mTLS/DPoP on each renewal.
Absolute expirationlimit total durationrequire new authorization after a defined period.
Inactivityclose abandoned authorizationsrenew only while there is legitimate use.
Revocationrespond to risk and shutdownpropagate quickly and audit motif.

16.14 Access tokens, scopes, audience and resource indicators

must only be accepted by the for which it was issued. Wide audience turns a token into a reusable pass between APIs. Resource Indicators allow the to declare the intended resource during authorization or token request, helping the to issue specific tokens.

represents authority requested and granted, but its semantics must be documented. Scopes like read and write are simple, but can be ambiguous on large platforms. Domain, operation and resource names help: payments.read, payments.create and conciliacao.execute. does not replace object, tenant, or domain authorization.

The validates the audience, and context of the request. An API should not accept a token because it contains “admin” without checking the issuer, type and origin of the claim. Authorization claims need to have governance: who issues them, when they change, how they are revoked, and which service has the authority to interpret them.

Resource Indicator - conceptual example

GET /authorize?response_type=code
  &client_id=app
  &resource=https%3A%2F%2Fapi.payments.example
  &scope=payments.read
Table 9 - Technical validation and business authorization are complementary.
ElementValidation question
audiencewas this token issued for this API or gateway?
scopeDoes the authority granted include the operation?
subject/clientWho is the principal and which application operates?
tenantdo principal and resource belong to the permitted context?
token typeis the artifact an expected access token, not ID token or another JWT?

16.15 Opaque tokens, and revocation

Opaque token does not reveal structure to the or . The API queries the by or uses distributed local . This approach facilitates immediate revocation and minimizes claim exposure, but creates dependencies on availability, latency, API authentication and caching policy.

returns active and authorized attributes for the requester. active=false should be normal response for invalid, expired, revoked or unknown token, without revealing details. The endpoint needs to authenticate resource servers and limit what data each one can query. Cache reduces load, but increases the window between revocation and enforcement.

Revocation allows the to request invalidation. The successful response should not reveal whether the token existed. Revoking normally terminates the ability to renew; Access tokens already issued can continue until they expire if they are self-contained. High-risk architectures combine short TTL, , revocation or denylist events.

- simplified example

POST /introspect
Authorization: Basic <resource-server-credential>
Content-Type: application/x-www-form-urlencoded
token=OPAQUE_TOKEN
HTTP/1.1 200 OK
{
  "active": true,
  "client_id": "portal",
  "scope": "payments.read",
  "exp": 1770000000
}

16.16 JWT access tokens and validation

JWT allows the to locally validate signatures and claims, reducing calls to the . The profile standardizes claims and useful types, but the API still needs to know issuer, audience, algorithms and trusted keys. Decoding Base64URL is not validating.

Validation must fix allowed algorithms, locate the key by the kid in trusted JWKS, check signature, issuer, audience, expiration, not-before when present and expected type. The must reject tokens issued for other use, even if the same key signs ID tokens. typ and profile rules help prevent confusion between JWT types.

Key rotation requires caching and controlled updating. When unknown kid appears, the gateway can update JWKS, but must not allow the token to point to an arbitrary key URL. Temporary metadata failure should not immediately invalidate all still trusted keys; at the same time, excessive caches delay compromised key removal.

Table 10 - Valid signature is just one of the checks.
ValidationFailure to avoid
signature and fixed algorithmaltered token or algorithm confusion.
exact issueruntrusted domain token.
audiencereuse in another API.
exp/nbf/clockuse outside the permitted window.
type/profileconfusion between access token, ID token and other JWTs.
scopes and claimsoperation beyond the authority granted.

Unencrypted content

A signed JWT typically protects integrity, not confidentiality. Avoid unnecessary PII and data. The token passes through clients, proxies, gateways, tools and logs; treat it as sensitive credential.

Consent is a decision interface, not a substitute for policy. In corporate environments, some permissions are approved by administrators or contracts, while others depend on the user. The screen must identify customer, data, actions, duration and consequences, avoiding incomprehensible technical scopes.

Least privilege starts with the definition of scopes and continues on the . Requesting all scopes “to avoid new consent” increases the impact of leaks. Incremental authorization allows you to request additional authority only when the functionality is used. The can subset and the needs to verify the response.

Rich Authorization Requests represent structured details such as amount, currency, account, and transaction type. This allows for more precise authorizations than strings, especially on payments and financial data. The authorization object must be validated, signed or protected according to the adopted profile and must not be accepted as free data sent by the to the API.

Rich Authorization Request - teaching example

{
  "authorization_details": [{
    "type": "payment_initiation",
    "instructedAmount": {"currency": "BRL", "amount": "150.00"},
    "creditorAccount": {"iban": "EXAMPLE"}
  }]
}

16.18 , and

Pushed Authorization Requests allow the to send parameters to the via back-channel and receive short-lived request_uri. The browser only carries the reference. This reduces manipulation, exposure, and URL length, and allows for authentication prior to user interaction.

JWT-Secured Authorization Request represents the request in a signed and, optionally, encrypted JWT. The validates the integrity and origin of the parameters. and can be combined: the sends a signed request object to the endpoint and uses the request_uri in the authorization endpoint.

secures the authorization response in a signed or encrypted JWT. Instead of relying solely on loose parameters in the redirect, the validates issuer, audience, signature and time. These mechanisms increase complexity and key management, which is why they are more common in financial profiles, regulated ecosystems and high-risk integrations.

Table 11 - Mechanisms protect different stages of the front-channel.
MechanismProtectsBenefit
PARsending parametersauthenticated back-channel and shortened URL.
JARrequest contentintegrity, origin and possible confidentiality.
JARMauthorization responseverifiable signature, issuer and audience.
Comparison between bearer token and sender-constrained token
Figure 4 - Proof-of-possession reduces the utility of a copied token.

16.19 Sender-constrained tokens with mTLS and

works like bearer money: whoever obtains the value can present it. binds the to a key. The requires, in addition to the token, corresponding proof of ownership. The goal is to reduce replay after leaks in logs, proxies, memory or side channels.

With mTLS, the associates the token with the 's certificate and the verifies the certificate presented in the connection. The claim cnf can load thumbprint. The architecture needs to ensure that the API observes the correct TLS identity even when there are load balancers or gateways terminating connections.

uses a proof JWT signed by the in each request, containing HTTP method, URI, time, unique identifier and link to the . The API validates signature, htm, htu, iat, jti, key and ath. is application layer protection and does not replace TLS. Server nonce and jti cache can strengthen replay defense according to risk.

Table 12 - The choice depends on client, infrastructure and risk.
MechanismBondStrong pointChallenge
mTLScertificate on connectionstrong for controlled customers and servicesproxies, PKI and TLS termination.
DPoPkey and proof upon requestapplicable without client certificateURI, clock, jti and key validation.
Bearernonesimplicity and compatibilityreplay after token copy.

16.20 and on-behalf-of

In service architectures, the first backend may need to call another while retaining some of the original authority. Forwarding the same to all services broadens audiences and exposes the credential. allows you to exchange a subject token for another token appropriate to the next resource.

The new token can represent the user, the actor service, or both. Actor claims help record the chain. The policy should limit which clients can exchange tokens, which audiences can be solicited, and which scopes can be preserved. The exchange must not elevate privilege beyond the entry token and the actor's authority.

On-behalf-of is an implementation of delegation where a service acts on behalf of the user. Logs need to preserve user, initial , intermediate service and effective authorization. If a call passes through several trust domains, each issue must be treated as a new decision, not as a simple copy of headers.

Table 13 - Preserve context without indiscriminately reusing authority.
StrategyAdvantageRisk
Forward original tokensimplewide audience, leakage and coupling.
Token Exchangespecific token per hoppolicy complexity and correlation.
Service credential onlyseparates backendloses user context when it is needed.

16.21 Metadata of the and protected resource

Metadata publishes issuer, endpoints, authentication methods, grants, scopes and algorithms. Clients must obtain the source document configured and validate consistency between issuer and URL. Metadata simplifies rotation and interoperability, but it should not turn discovery into automatic trust.

Protected Resource Metadata allows an API to publish resource identifiers, related authorization servers, scopes, and supported presentation methods. This helps clients and authorization servers understand how to obtain tokens for a resource and improves WWW-Authenticate challenges.

Metadata must be versioned and monitored as part of the platform. Changes to endpoint, algorithm or issuer can break all clients. Cache needs to respect availability without freezing configuration indefinitely. Internal, external and approval environments must have separate documents to prevent mixing of trust.

Metadata - illustrative excerpt

{
  "issuer": "https://id.example",
  "authorization_endpoint": "https://id.example/authorize",
  "token_endpoint": "https://id.example/token",
  "jwks_uri": "https://id.example/jwks.json",
  "code_challenge_methods_supported": ["S256"]
}
OAuth in enterprise architecture with API Gateway and backend
Figure 5 - The gateway acts as transversal enforcement; domain authorization remains in the backend.

16.22 OAuth on API Gateways, Axway and Azure

API Gateways can validate access tokens, query , require scopes, enforce quota by client_id, and propagate trusted context. Before inserting internal headers, the gateway must remove -supplied versions. The backend must accept these headers only from an authenticated connection coming from the gateway.

In Azure API Management, validate-jwt and validate-azure-ad-token can validate tokens before the backend. Policies can require issuer, audience and claims, while authentication-managed-identity allows the gateway to obtain token for a compatible backend. Configuring the developer portal for OAuth facilitates testing, but does not replace policy enforcement.

In Axway API Gateway, OAuth filters and services can implement , token validation, authentication, and policies. The topology needs to record which component issues, which validates, where keys are stored and how revocation and rotation are handled. As versions and licenses change, validate the installed product documentation.

Azure API Management - conceptual policy

<validate-jwt header-name="Authorization"
              require-expiration-time="true"
              require-signed-tokens="true">
  <openid-config url="https://id.example/.well-known/openid-configuration" />
  <audiences><audience>api://payments</audience></audiences>
  <required-claims>
    <claim name="scp" match="any"><value>payments.read</value></claim>
  </required-claims>
</validate-jwt>

Division of responsibility

The gateway validates issuer, audience, signature, time, scopes and transversal requirements. The backend continues checking tenant, ownership, transaction status, business limits and object authorization.

16.23 Threats and hardening

interception is reduced by . CSRF and CSRF login require and transactional binding. Mix-up requires association with the issuer. Redirect URI manipulation requires exact comparison. Token leakage requires TLS, log hygiene, correct headers, secure storage and TTL reduction. Token replay may require sender constraint.

Open redirectors on the or increase code bypass. Referrer, history and analytics can capture front-channel parameters. Query string tokens leak easily and should not be used as a normal form of presentation. Access tokens must follow Authorization header and responses need proper Cache-Control.

Authorization servers must protect endpoints against brute force, credential stuffing, request flooding and user_code abuse. Clients need to validate all responses and not display internal details. Resource servers must limit algorithms, validate audiences and not trust claims without namespace and governance. Every implementation requires an inventory of clients, owners, grants, redirect URIs and keys.

Table 14 - Controls must produce observable evidence.
ThreatMain controlEvidence
Code interceptionPKCE S256 and single-use codeverifier failures and reuse.
CSRF/login injectionsession-bound statestate absent, divergent or consumed.
AS mix-uplinked issuer and metadataresponse issuer and token endpoint used.
Token replayTTL, mTLS/DPoP and detectionjti, thumbprint and origin.
Refresh token theftrotation and reuse detectionrevoked family and risk event.
Redirect abuseexact comparison and without open redirectRegistered URI and received URI.

Inadvisable practices

Do not use Implicit or Password Credentials in new projects. Do not store client_secret in . Do not accept redirect URI by prefix. Do not treat ID token as . Don't accept JWT just because it “decoded without error”.

16.24 Evidence-driven troubleshooting

Diagnosis begins by identifying the endpoint and step. Error in authorization endpoint involves parameters, session, policy and redirect URI. Token endpoint error involves authentication, code, verifier, and clock. API error involves presentation, validation and authorization. Mixing these steps turns invalid_grant into “Invalid JWT” or 403 into “login failure”.

Collect correlation ID, expected issuer, client_id, grant_type, normalized redirect URI, scopes, audience, kid, time and status without registering tokens or codes. Compare the clock of the components. Confirm metadata and JWKS accessed by the runtime, not just the operator's notebook. In proxy environments, record hostname, TLS, and actual destination.

For intermittency, investigate key rotation, multiple nodes with divergent caching, concurrent or reuse, load balancing without session affinity, and DNS. Reproduce with a single controlled flow and synthetic tokens. A token may work on one gateway and fail on another due to different configuration or cache.

Table 15 - Classify the step before changing policies.
ErrorInitial hypothesesEvidence
invalid_requestmissing, duplicate or incompatible parameternormalized request and metadata.
invalid_clientmethod, secret, certificate or assertionclient_id, auth method, jti and certificate thumbprint.
invalid_grantexpired/used code, PKCE, redirect URI or refresh revokedtransaction status and usage history.
invalid_tokensignature, issuer, audience, time or revocationinternal reason code and kid.
insufficient_scopevalid token no authority requiredscope granted and operation policy.
401/403 divergentdifferent layers respondedVia, Server, request-id and correlated logs.

Stable external error; Detailed cause remains in the secure log

HTTP/1.1 401 Unauthorized
WWW-Authenticate: Bearer realm="payments",
  error="invalid_token"
Content-Type: application/problem+json
{
  "type": "https://errors.example/oauth/invalid-token",
  "status": 401,
  "correlationId": "corr-8f12"
}

16.25 Case studies

Case 1 - SPA with built-in secret

A SPA sends client_secret in the token request. The value is visible in the bundle and can be copied by any user. The fix is to register the as public, use with and exact redirect URI. If the risk of tokens in the browser is high, adopt BFF and cookie protected.

The investigation also checks CORS, token storage, XSS, logout, and renewal. Just removing the secret does not resolve exposure of or persisted in localStorage.

Case 2 - Token accepted by wrong API

Two APIs trust the same issuer and key, but one of them does not validate audience. A token issued for reporting is accepted for payments. The fix is to require specific audience and separate scopes. In critical systems, resource indicators and resource tokens reduce the possibility of cross-reuse.

Security contract tests must send valid tokens to neighboring audiences and expect rejection. This negative check needs to exist on gateway and backend when both validate tokens.

Case 3 - reused after timeout

The uses a , receives timeout and repeats the call. The first processing had issued a new token; repetition looks like theft and the family is revoked. The solution combines operational idempotence, controlled tolerance window or logic that serializes renewal and handles lost responses.

A wide tolerance weakens reuse detection. The decision must consider risk, network and ability to correlate attempts. Logs need to record family, predecessor token, and result without storing the raw value.

Case 4 - Gateway validates, backend rejects

The gateway accepts the token for its own audience and forwards it to the backend, which expects the token intended for it. The architecture needs to choose: backend trusts the context propagated by the gateway in an authenticated channel, or gateway obtains a new token for the backend using managed identity, or .

Forwarding the original token is only correct when the backend is the for that audience. The decision must be documented in the security contract and tested with multiple APIs.

Observation labs

Lab 1 - with

  • Use a laboratory or authorized simulator.
  • Generate random verifier and S256 challenge.
  • Run the correct flow and record only synthetic values.
  • Repeat with wrong verifier, divergent , reused code and changed redirect URI.
  • Classify each error by step and endpoint.

Lab 2 - audience and validation

  • Configure two APIs with different audiences.
  • Issue token for API A and try to use it on API B.
  • Test missing, expired and alternative issuer.
  • Compare external response and internal reason code.

Lab 3 - and cache

  • Use opaque lab and token endpoints.
  • Measure no-cache and short-cache latency.
  • Revoke the token and watch the window until rejection.
  • Document the decision between availability and speed of revocation.

Lab 4 - rotation

  • Obtain a synthetic .
  • Renew and confirm issuance of successor.
  • Reuse the predecessor and observe family policy.
  • Simulate two competing renewals and analyze the result.

Lab 5 - policy at the gateway

  • Configure issuer, audience and in lab gateway.
  • Unknown kid test and JWKS update.
  • Remove -sent identity headers.
  • Only propagate validated claims and compare with backend authorization.

Chapter summary

OAuth 2.0 is a delegation framework. , , and have different responsibilities. Authorization endpoint and token endpoint use different channels, and each artifact - code, , and ID token - has its own recipient and lifecycle.

with is the modern basis for user-based applications. protects against interception, links the transaction, nonce belongs to the OIDC and issuer protects multi-issuer clients. Public clients do not have reliable secrets; confidential clients can use secret, private_key_jwt or mTLS.

represent the application, Device Authorization meets limited input and refresh tokens require rotation or sender constraints. Access tokens need a minimum audience and . Opaque tokens favor central control; JWTs favor local validation, but require full verification and key management.

, , and RAR strengthen requests and responses; mTLS and reduce replay; controls delegation between services. API Gateways apply cross-cutting validation, while backends preserve domain authorization. Security depends on inventory, least privilege, exact redirect URI, log hygiene, observability, and negative testing.

Next step of the course

Chapter 17 will delve deeper into OpenID Connect: ID Token, UserInfo, nonce, acr, amr, federated authentication, sessions, logout, and secure application integration with identity providers.

OAuth 2.0 Checklist

  • Each has explicitly registered owner, type, redirect URIs and grants.
  • uses S256, including for confidential clients.
  • is random, single-use and linked to issuer, redirect URI and verifier.
  • Public clients do not depend on client_secret.
  • Redirect URIs use exact matching and do not contain open redirectors.
  • Implicit and password grants are not used on new projects.
  • Access tokens have minimal audience and scopes.
  • ID token is not accepted as an .
  • Refresh tokens have rotation, sender constraint or equivalent policy.
  • JWTs validate signature, algorithm, issuer, audience, type and time.
  • is authenticated and has revocation-aware caching.
  • Tokens do not appear in URLs, logs, analytics or error messages.
  • mTLS or is considered for high replay risk.
  • Gateway and backend have explicit authorization division.
  • Rotation of JWKS, certificates and is tested.
  • OAuth errors are correlatable without revealing sensitive details.
  • Customers, grants, consents and tokens have a termination process.

Exercises

  • Explain why OAuth 2.0 is not, on its own, a user authentication protocol.
  • Differentiate , , and ID token.
  • Describe checks with .
  • Explain why and are not substitutes for each other.
  • Rate a SPA and justify why its client_secret is not trustworthy.
  • Compare client_secret_basic, private_key_jwt and mTLS.
  • Model for a userless job.
  • Explain reuse detection in rotation.
  • Compare opaque token with JWT on revocation and availability.
  • List mandatory validations of a .
  • Explain audience and resource indicators on a platform with multiple APIs.
  • Compare , and .
  • Differentiate between mTLS-bound token and -bound token.
  • Propose for three services while preserving the user.
  • Create a troubleshooting script for intermittent invalid_grant.

Glossary

Table 16 - Essential vocabulary of the chapter.
TermDefinition
Access tokenCredential presented to the resource server to exercise authority.
Authorization codeShort, single-use grant exchanged on the token endpoint.
Authorization serverComponent that evaluates authorization and issues tokens.
Bearer tokenToken usable by any holder of the value.
ClientApplication that requests and uses authority.
Client CredentialsGrant in which the application acts on its own behalf.
Confidential clientClient capable of protecting authentication credentials.
device_codeArtifact used in Device Authorization Grant polling.
DPoPProof by request that links token to a key.
GrantAuthorization representation used to obtain token.
IntrospectionAuthenticated query on activity and token attributes.
JARProtected authorization request in JWT.
JARMProtected authorization response in JWT.
JWT access tokenAccess token structured and signed according to profile.
PARSending parameters in advance via back-channel.
PKCEProof that links the code exchange to the client instance.
Public clientClient unable to reliably maintain secrecy.
Refresh tokenCredential used to obtain new access tokens.
Resource ownerEntity capable of granting access to the resource.
Resource serverAPI that accepts access tokens and protects resources.
ScopeTextual representation of authority requested or granted.
Sender-constrained tokenToken tied to proof of a customer key.
StateValue that links request and response and helps against CSRF.
Token ExchangeGrant to exchange a token for another suitable for a new context.

Annex A - Flow choice matrix

Table 17 - The final choice depends on platform, risk and customer capacity.
ScenarioInitial flowEssential controls
Web application with userAuthorization Code + PKCEconfidential client, state, cookie protected and exact redirect URI.
pure SPAAuthorization Code + PKCEpublic client, XSS hardening, short token and no secret.
Higher risk spaBFF + Authorization Code + PKCEserver-side tokens, CSRF and HttpOnly/SameSite cookie.
Native AppAuthorization Code + PKCEexternal browser, app/universal link and system storage.
Service to serviceClient Credentialsprivate_key_jwt, mTLS or workload identity; minimum audience.
Limited deviceDevice Authorization GrantExpirable user_code, controlled polling and anti-phishing.
Service chainToken Exchange / on-behalf-ofaudience per hop, actor and correlation.
Regulated ecosystemCode + PKCE + PAR/JAR/JARMRAR, sender constraint, signature and reinforced auditing.

Technical references

  • IETF. RFC 6749 - The OAuth 2.0 Authorization Framework. 2012.
  • IETF. RFC 6750 - OAuth 2.0 Usage. 2012.
  • IETF. RFC 7009 - OAuth 2.0 Token Revocation. 2013.
  • IETF. RFC 7519 - JSON Web Token (JWT). 2015.
  • IETF. RFC 7636 - Proof Key for Code Exchange by OAuth Public Clients. 2015.
  • IETF. RFC 7662 - OAuth 2.0 Token . 2015.
  • IETF. RFC 8252 - OAuth 2.0 for Native Apps. 2017.
  • IETF. RFC 8414 - OAuth 2.0 Metadata. 2018.
  • IETF. RFC 8628 - OAuth 2.0 Device Authorization . 2019.
  • IETF. RFC 8693 - OAuth 2.0 . 2020.
  • IETF. RFC 8705 - OAuth 2.0 Mutual-TLS Authentication and Certificate-Bound access tokens. 2020.
  • IETF. RFC 8725 - JSON Web Token Best Current Practices. 2020.
  • IETF. RFC 9101 - JWT-Secured Authorization Request. 2021.
  • IETF. RFC 9126 - Pushed Authorization Requests. 2021.
  • IETF. RFC 9068 - JWT Profile for OAuth 2.0 access tokens. 2021.
  • IETF. RFC 9207 - OAuth 2.0 Issuer Identification. 2022.
  • IETF. RFC 9396 - OAuth 2.0 Rich Authorization Requests. 2023.
  • IETF. RFC 9449 - OAuth 2.0 Demonstrating Proof of Possession. 2023.
  • IETF. RFC 9700 - Best Current Practice for OAuth 2.0 Security. 2025.
  • IETF. RFC 9701 - JWT Response for OAuth Token . 2025.
  • IETF. RFC 9728 - OAuth 2.0 Protected Resource Metadata. 2025.
  • IETF OAuth Working Group. The OAuth 2.1 Authorization Framework - Internet-Draft, version consulted in 2026.
  • Microsoft Learn. Azure API Management authentication, validate-jwt, validate-azure-ad-token, and managed identity policies.
  • Axway Documentation. OAuth 2.0 services, authentication and token validation on API Gateway.
  • OpenID Foundation. Financial-grade API Security Profile and OpenID Connect specifications, when applicable to the ecosystem.

Update note

OAuth evolves through RFCs, Best Current Practices, profiles and drafts. Before deploying a flow or policy, validate the current specification, product version documentation, and behavior in an authorized environment. Treat Internet-Drafts as work in progress, not as automatic replacements for RFCs.