Skip to main content

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 a generate_pkce() helper that creates a cryptographically random code verifier and its S256 challenge.

Usage

Import

PkceChallenge

generate_pkce() returns a PkceChallenge frozen dataclass:

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 the code_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 the code_verifier in the token exchange:
The server verifies that SHA256(code_verifier) == code_challenge before issuing the token. If the verifier does not match, the exchange is rejected.

Full Example

How It Works

  1. generate_pkce() creates 32 random bytes and base64url-encodes them to produce the code_verifier.
  2. The code_challenge is the SHA-256 digest of the verifier, base64url-encoded (without padding).
  3. The challenge method is always S256 (plain is not supported).
  4. During token exchange, the server independently computes SHA256(code_verifier) and compares it to the stored code_challenge. A mismatch causes the exchange to fail.
Last modified on February 28, 2026