Overview
PKCE (Proof Key for Code Exchange) prevents authorization code interception attacks by binding the authorization request to the token exchange. The Grantex SDK provides agenerate_pkce() helper that creates a cryptographically random code verifier and its S256 challenge.
Usage
Import
PkceChallenge
generate_pkce() returns a PkceChallenge frozen dataclass:
| Field | Type | Description |
|---|---|---|
code_verifier | str | A cryptographically random URL-safe string (32 bytes, base64url-encoded). |
code_challenge | str | The SHA-256 hash of the verifier, base64url-encoded. |
code_challenge_method | str | Always "S256". |
Complete PKCE Flow
The PKCE flow has three steps: generate the challenge, authorize with the challenge, and exchange with the verifier.Step 1: Generate the PKCE Pair
Step 2: Authorize with the Code Challenge
Pass thecode_challenge and code_challenge_method in the authorization request:
Step 3: Exchange with the Code Verifier
After the user approves and you receive the authorization code at your redirect URI, include thecode_verifier in the token exchange:
SHA256(code_verifier) == code_challenge before issuing the token. If the verifier does not match, the exchange is rejected.
Full Example
How It Works
generate_pkce()creates 32 random bytes and base64url-encodes them to produce thecode_verifier.- The
code_challengeis the SHA-256 digest of the verifier, base64url-encoded (without padding). - The challenge method is always
S256(plain is not supported). - During token exchange, the server independently computes
SHA256(code_verifier)and compares it to the storedcode_challenge. A mismatch causes the exchange to fail.