Securing OAuth 2.0 Applications: Authorization Code Flow, PKCE and Token Security

A login screen is only one part of an application's identity architecture. Behind it, authorization codes, access tokens, redirect endpoints and application sessions determine whether a user can safely interact with protected resources. A mistake in any of these components can undermine an otherwise well-designed application.
OAuth 2.0 provides a framework for delegated access. It does not, by itself, define an authentication protocol. OpenID Connect (OIDC) adds the identity layer needed by applications that want to establish who has signed in.
This guide explains how to combine authorization code flow, Proof Key for Code Exchange (PKCE) and careful token handling. It focuses on browser applications, backend services and mobile clients using an established authorization server. All hostnames and scenarios below are fictional.
1. Understand the participants and their responsibilities
Consider a reporting portal that lets a user view documents through a protected API. Instead of collecting the user's identity-provider password, the portal redirects the user to a trusted authorization server and requests narrowly scoped access.
| Participant | Responsibility |
|---|---|
| Resource owner | Authorizes access to protected information |
| Client | Requests and uses the delegated access |
| Authorization server | Issues authorization codes and tokens |
| Resource server | Enforces access to the protected API |
These responsibilities may be hosted by different systems. The API must make its own authorization decision, even if the user has already authenticated successfully at the identity provider.
An access token represents authorization to access resources. An ID token communicates authentication information to its intended OpenID Connect client. A refresh token is a credential used to request new access tokens, subject to the authorization server's policy. Do not treat the three as interchangeable.
For example, an ID token intended for the reporting portal should not be accepted by the reporting API as if it were an access token. That distinction prevents an application from confusing proof of sign-in with permission to perform a particular business operation.
2. Choose the appropriate client architecture
Different application types have different credential-storage capabilities. A browser-only JavaScript application or distributed mobile app cannot reliably keep a static client secret confidential. A properly controlled backend can.
| Application type | Recommended architectural direction |
|---|---|
| Server-rendered web application | Authorization code flow with PKCE and server-side token handling |
| Browser-only application | Authorization code flow with PKCE, with carefully designed browser token handling |
| Native mobile application | Authorization code flow with PKCE through the system browser |
| Machine-to-machine service | Client credentials when acting on its own behalf, with appropriately secured client authentication |
A confidential web application should authenticate itself to the token endpoint using its configured method. PKCE complements that authentication; it does not replace it.
For native apps, use the platform's external browser and an appropriate redirect mechanism instead of collecting credentials inside an embedded browser. RFC 8252 describes the native application model.
A backend-for-frontend (BFF) can be valuable for browser applications that handle sensitive operations. The backend retains OAuth tokens, while the browser receives a protected application-session cookie. This reduces direct token exposure to browser JavaScript, but introduces session management and CSRF responsibilities. It does not eliminate the risk that malicious scripts act through an authenticated session.
3. Follow the authorization code flow
A typical application begins by creating a short-lived authorization transaction. The client then directs the user's browser to the authorization endpoint.
User browser -> Client: Start sign-in Client -> Browser -> Authorization server: Authorization request Authorization server -> Browser -> Client: Authorization code Client -> Authorization server: Code exchange with PKCE Client -> Resource API: Access token
The code is a temporary credential, not a token that should be reused for API requests. The authorization server checks the code exchange before returning tokens.
Keep the authorization server's issuer, endpoints and client registration in trusted configuration. For clients supporting multiple identity providers, bind the selected issuer to the authorization transaction and enforce the applicable issuer or mix-up protection. Do not choose the token endpoint from arbitrary callback parameters.
Use a registered redirect URI, such as the following fictional web callback:
https://portal.example.invalid/oauth/callback
The authorization server should enforce exact redirect matching, subject to the documented native loopback exception. The application must also avoid forwarding users to untrusted destinations through a generic callback or post-login redirect parameter.
4. Generate PKCE values correctly
PKCE connects an authorization request to the client instance that initiated it. The client creates a random verifier and derives a challenge. The authorization server stores the challenge with the code and checks the verifier during token exchange.
The following original Python example uses only the standard library. It demonstrates value generation, not a complete OAuth client.
import base64
import hashlib
import secrets
def base64url(data: bytes) -> str:
return base64.urlsafe_b64encode(data).rstrip(b"=").decode("ascii")
def create_pkce() -> tuple[str, str]:
verifier = base64url(secrets.token_bytes(32))
challenge = base64url(
hashlib.sha256(verifier.encode("ascii")).digest()
)
return verifier, challenge
verifier, challenge = create_pkce()
assert len(verifier) == 43
assert len(challenge) == 43
The verifier has 256 bits of source randomness, and the challenge uses SHA-256 with unpadded Base64URL encoding. Generate a new pair for every authorization transaction. Retain the verifier securely until the corresponding callback is processed.
The authorization request includes the challenge and specifies the S256 method. The token request includes the original verifier. Avoid silent fallback to the plain method.
RFC 7636 defines the PKCE mechanism and encoding requirements.
5. Bind the callback to the initiating session
PKCE is one component of a complete authorization transaction. An application must also ensure that the returned response belongs to the correct user interaction and identity provider.
A practical server-side design stores a random state value, the verifier, expected issuer, redirect URI and expiry together. If using OIDC, include a random nonce and validate it in the returned ID token when one was sent.
On receiving the callback, look up the transaction associated with the current application session, compare the returned state and enforce expiry. Reject unexpected or repeated responses. Consume the transaction atomically so two simultaneous callbacks cannot both complete the same session exchange.
Use an established OAuth or OIDC library for request construction, response parsing, token exchange and protocol validation. The PKCE example above is educational and does not replace these facilities.
RFC 9700, published in January 2025, describes the security baseline for modern OAuth deployments. Review its recommendations when migrating older applications, particularly those using the implicit grant or resource owner password credentials grant.
6. Validate access tokens at the API boundary
A common integration error is accepting a token merely because it can be decoded. Decoding is not verification.
For a signed JWT access token, configure a trusted issuer and the issuer's verification keys using an established validation library. Enforce the intended API audience, expiry, accepted algorithms and the applicable token profile. Handle key rotation without trusting arbitrary key locations supplied by token contents.
If the provider issues tokens conforming to the RFC 9068 JWT access token profile, also enforce its token-type and claim requirements. Not every provider uses that exact profile, so establish the contract before selecting validation rules.
An opaque token does not expose the same local claims. The API can consult an authenticated introspection endpoint to establish whether it is active and obtain the necessary authorization context. RFC 7662 defines this approach.
Successful token validation is not the end of authorization. Suppose a token permits reading reports. The API still must check that the requested report belongs to a tenant or account the caller is allowed to access. A broad read scope alone must not grant unrestricted access across customers.
7. Protect token storage and lifecycle
Treat tokens as credentials. Keep them out of application logs, analytics events, URL parameters and exception messages. Use encrypted transport and protect the systems that store server-side credentials.
Prefer limited access-token lifetimes appropriate to the application. Shorter lifetimes reduce the period during which a stolen bearer token may remain useful, but increase renewal frequency and dependence on the authorization server.
Where refresh tokens are issued to public clients, the deployment must support an appropriate replay protection mechanism, such as sender constraining or refresh-token rotation, in accordance with the security BCP. Coordinate parallel refresh requests so that legitimate concurrent browser activity does not unnecessarily trigger reuse detection.
For high-value APIs, evaluate sender-constrained tokens and the operational costs of key management. Establish a revocation and session termination strategy; removing a browser session does not necessarily invalidate every previously issued access token immediately.
In a BFF architecture, configure session cookies with Secure, HttpOnly and an appropriate SameSite policy, and implement CSRF protection for state-changing requests. Ensure cookie settings are compatible with the chosen callback response mode.
8. Verify the integration before release
Use a dedicated test environment with synthetic identities and test clients. Record both permitted and rejected outcomes.
| Test scenario | Expected behavior |
|---|---|
| Correct authorization transaction | Session established successfully |
| Invalid or expired transaction state | Callback rejected |
| Incorrect PKCE verifier | Token exchange rejected |
| Unregistered redirect URI | Authorization request rejected |
| Expired access token | Protected request rejected |
| Token intended for another API | Protected request rejected |
| Valid token without required permission | Business operation denied |
| Logout and session expiry | Session termination follows policy |
Test signing-key rotation, concurrent login attempts, multiple browser tabs and refresh-token handling. Monitor unexpected callback failures, invalid token rates and authorization denials without recording the credentials themselves.
Maintain separate client registrations and redirect URLs for development, staging and production. Review the permitted scopes and grant types whenever an integration changes. A broad production registration should not become the default template for every new application.
Conclusion
Secure OAuth integrations depend on clear client boundaries, a well-bound authorization transaction and independent resource authorization. Authorization code flow with PKCE provides a solid starting point, while token handling, issuer validation, session security and carefully scoped permissions complete the design.
Use established libraries, apply the identity provider's documented token contract and test negative cases before connecting sensitive systems. A successful login is not proof that every subsequent API request is authorized.


