OAuth PKCE Explained: S256, Verifier, and State
Understand OAuth PKCE with Authorization Code, S256, state, and nonce. Includes a tested Python challenge example and practical verifier-mismatch checks.
PKCE binds an authorization-code exchange to a secret created for that authorization attempt. Send an S256 challenge in the authorization request and the original verifier at the token endpoint. Keep the verifier transaction-specific, preserve the client library’s session protections, and validate the resulting tokens as required by the flow.
What possession of an authorization code should prove
In an authorization-code flow, the browser returns a short-lived code to the client’s redirect URI. The client exchanges that code at the token endpoint. If another party obtains the code, the token endpoint needs more evidence than possession of that value alone. PKCE adds a transaction-specific proof to this exchange.
The client creates a secret verifier before sending the authorization request. It sends a derived challenge with that request and presents the original verifier only during the token exchange. The authorization server associates the challenge with the issued code and checks the proof before issuing tokens.
This guide follows RFC 7636 and the OAuth security guidance in RFC 9700. The latter requires PKCE for public clients and recommends it for confidential clients in authorization-code flows. For a new implementation, choose a maintained OAuth/OIDC library with S256 support and review the provider’s integration contract.
Source: RFC 7636: PKCE protocol and Appendix B test vector ↗
Keep the values and endpoints separate
Think of the challenge as a commitment made before the code exists. With S256, it is the unpadded base64url encoding of a SHA-256 digest of the ASCII verifier. The server can later check that the token request supplies the verifier corresponding to that earlier commitment. Hashing a new verifier after the redirect cannot satisfy the original challenge.
The verifier must remain available to the same pending transaction until the callback is processed or the transaction expires. A single global verifier variable creates a race when a user opens two authorization attempts. Store transaction data using the library’s supported mechanism, bound to the appropriate user-agent session and expected authorization server.
The authorization endpoint is visited through the user agent. The token endpoint receives the code exchange. An API resource server receives an access token for the protected resource. Mixing these destinations is a useful way to recognize a broken integration before debugging cryptography.
| Value | Where it belongs | How to treat it |
|---|---|---|
| code_challenge | Authorization request | Derived commitment; use S256 |
| code_verifier | Token request and pending transaction | Secret, fresh per authorization attempt |
| authorization code | Callback, then token request | Short-lived exchange credential |
| state | Authorization request and callback correlation | Follow library CSRF/session-binding design |
| access token | Calls to intended resource server | Credential; limit exposure |
| OIDC nonce | OIDC request and ID Token validation | Bind the identity response as required by the flow |
Source: RFC 9700: OAuth 2.0 Security Best Current Practice ↗
Follow one transaction from request to token exchange
The following sequence describes one authorization attempt. Error callbacks, cancellations, expiration, multiple tabs, and retries all need explicit handling in an actual application. Use the library’s transaction handling rather than assembling a login system from a URL builder and a hash function.
A redirect URI should match the registered client configuration and the request’s expected value. Do not accept an arbitrary callback destination supplied by a caller. Native apps have specific redirect options and platform rules; their loopback-port exception should not be generalized into loose redirect matching for every application.
| Step | Client action | Evidence to preserve |
|---|---|---|
| 1 | Create verifier and S256 challenge | Pending transaction, expected issuer and redirect URI |
| 2 | Redirect to authorization endpoint | Challenge method, client ID, scope and correlation values |
| 3 | Validate returned authorization response | Expected transaction and server; handle error or code |
| 4 | Send code and original verifier to token endpoint | Same redirect URI when required; client authentication if applicable |
| 5 | Validate token response and complete transaction | OIDC validation when used; consume transaction state |
Test the S256 transformation locally
The following Python example demonstrates only the verifier/challenge relationship. It makes no network requests, processes no callback, and stores no production credentials. Save it as pkce_demo.py and run it with Python 3. The fixed public test vector comes from RFC 7636 Appendix B and must never become a real transaction’s verifier.
The helper checks the permitted verifier length and ASCII character set before computing the digest. The fresh pair uses 32 random bytes via secrets.token_urlsafe, producing a 43-character verifier. Format validation alone cannot establish randomness: a predictable string may pass the format check while remaining unsuitable for authorization.
Notice that the code hashes the verifier bytes, not its hexadecimal hash string, and removes base64 padding after URL-safe encoding. It does not URL-encode the verifier before hashing. The assertions provide a quick way to detect common implementation mistakes without involving browser state or a provider account.
import base64
import hashlib
import re
import secrets
def s256_challenge(verifier: str) -> str:
if re.fullmatch(r"[A-Za-z0-9._~-]{43,128}", verifier) is None:
raise ValueError("Invalid PKCE verifier format")
digest = hashlib.sha256(verifier.encode("ascii")).digest()
return base64.urlsafe_b64encode(digest).rstrip(b"=").decode("ascii")
def new_pkce_pair() -> tuple[str, str]:
verifier = secrets.token_urlsafe(32)
return verifier, s256_challenge(verifier)
# Public RFC test data, never use for a real transaction.
vector = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk"
expected = "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM"
assert s256_challenge(vector) == expected
verifier, challenge = new_pkce_pair()
assert len(verifier) == 43
assert len(challenge) == 43
assert re.fullmatch(r"[A-Za-z0-9_-]{43}", challenge)
assert s256_challenge(verifier) == challenge
print("S256 checks passed; generated verifier is intentionally not printed.")Source: RFC 7636: PKCE protocol and Appendix B test vector ↗
Exchange the code with its original verifier
The token request adds code_verifier to the authorization-code exchange. It sends the original secret value, not the challenge. Use TLS and the provider’s token endpoint. A confidential client must also meet its client-authentication requirements; PKCE does not turn it into a public client or replace that authentication.
An SPA or installed native app cannot make an embedded static secret confidential merely by obfuscating it. Choose the client type and deployment architecture deliberately. For native apps, RFC 8252 calls for an external user agent rather than an embedded login browser under the app’s control.
The schematic body below illustrates field placement for a public client. It omits provider-specific behavior. Codes are short-lived and single-use; if an exchange outcome is uncertain, follow the library/provider recovery behavior instead of repeatedly submitting the same code or silently starting a second transaction.
POST /token HTTP/1.1
Host: auth.example.invalid
Content-Type: application/x-www-form-urlencoded
grant_type=authorization_code&client_id=example-client&code=RETURNED_CODE&redirect_uri=https%3A%2F%2Fclient.example.invalid%2Fcallback&code_verifier=ORIGINAL_VERIFIER
# Placeholder values only; no actual request is sent by this guide.Source: RFC 6749: authorization-code requests and token exchange ↗
PKCE, state, and nonce have related but distinct jobs
Keep the application’s correlation and CSRF design explicit. A one-time state value securely bound to the user agent is a familiar mechanism. If state carries a post-login navigation choice, protect its integrity and validate the destination; do not make it an open redirect.
RFC 9700 allows relying on PKCE for CSRF protection when authorization-server support is assured, and describes the conditions involved. That does not justify deleting a library’s state checks because you added code_challenge. Preserve the library’s documented protections and verify its assumptions rather than combining fragments from different flows.
In OpenID Connect, nonce connects an authentication request with the ID Token and helps detect replay. Validate ID Tokens according to the provider and OIDC rules, including signature, issuer, audience, lifetime, and nonce when used. Successfully redeeming a code is not the same as completing all identity-token validation.
Source: OpenID Connect Core: nonce and ID Token validation ↗
Diagnose failures by transaction, not by guessing another hash
An invalid_grant response is not a unique PKCE diagnosis. An expired or already used code, an inconsistent redirect URI, or other grant validation failures can produce it. Record a nonsecret transaction identifier and the processing stage, then use the provider’s error details to narrow the cause.
If a verifier mismatch is indicated, compare the stored transaction’s creation and callback events. Check whether the verifier was regenerated, overwritten by another tab, lost during navigation, or transformed before hashing. Verify S256, URL-safe base64, and omitted padding against the public vector. Never log the live verifier to make comparison easier.
If the callback cannot find a transaction, inspect session binding, cookie delivery, origin changes, and expiration. If token exchange succeeds but application sign-in fails, inspect OIDC validation and session establishment separately. Treat each stage as a distinct observation so one successful HTTP response does not conceal a later validation failure.
Source: RFC 6749: authorization-code requests and token exchange ↗
Review the request pair without exposing the proof
A practical review can compare the two request shapes without collecting their live values. On the authorization side, confirm that response_type is code and the challenge method is S256. On the token side, confirm that the original verifier is supplied through the expected form field. Record only whether each required field was present and which transaction record was selected.
Separate configuration mistakes from transaction mistakes. A wrong client registration or callback URL usually persists across fresh attempts; an overwritten verifier may appear only with two tabs or a resumed session. Reproduce those conditions deliberately in a test environment. Changing the hash algorithm cannot repair an incorrectly selected transaction record.
Turn the explanation into an integration test plan
For this publication we executed the Python transformation with CPython 3.12.14, checked the RFC vector, and tested accepted length boundaries and rejected malformed inputs. We also checked fresh generated pairs and that a changed verifier produces a different challenge. These are local helper checks; no authorization server or end-to-end login was tested.
For your actual provider, use an approved test client and verify that a wrong verifier fails, a missing verifier cannot downgrade a PKCE-bound code exchange, and an already consumed code cannot be reused. Exercise cancellation and concurrent authorization attempts. Expected failures belong in the test evidence, not just the successful login screenshot.
Use sanitized fixtures and a test identity appropriate for the environment. Confirm that application diagnostics exclude codes, verifiers, access tokens, and refresh tokens. A useful test report identifies the client library version, provider configuration, expected rejection, and observed stage without publishing credentials.
Source: RFC 9700: OAuth 2.0 Security Best Current Practice ↗
Know which risks remain after PKCE works
PKCE constrains use of a code to the party holding the transaction’s verifier. It does not sanitize application JavaScript, prevent all browser compromise, authorize an API action, or turn an access token into a verified user identity. A compromised client can expose both the verifier and the token it later receives.
Keep redirect validation, issuer checks, token handling, and session design in the same review. Scope access narrowly and send tokens only to the intended resource. If the application talks to multiple authorization servers, use the library’s documented issuer/mix-up defenses. These decisions need more than a correct SHA-256 function.
Adopt Authorization Code with S256 through a maintained integration, use the local example to understand its transformation, and test the provider’s rejection paths. The goal is one coherent transaction from authorization request to validated response, with the proof and session context preserved throughout.
Source: RFC 9700: OAuth 2.0 Security Best Current Practice ↗
Your next steps
- Use a maintained OAuth/OIDC client with Authorization Code and S256 support.
- Keep the verifier private and bound to one pending transaction; never send it in the authorization URL.
- Test both successful exchanges and rejection paths, with sanitized diagnostics and the provider’s validation rules.
Sources & official resources
Linked resources checked on 2026-10-23. Technical behavior and provider guidance can change; check the documentation for the version you use.
About this guide and its recommendations
Published by Prep With Proof with AI-assisted drafting. Study routines and examples are editorial suggestions, not official exam instructions or claims of a learner's personal results. Cited provider facts are linked; ownership of recommended Prep With Proof products is disclosed. No competitor endorsement or guaranteed certification outcome is implied.
Suggest a correction →