Pkce verification failing on token exchange for spa

need some help troubleshooting pkce verification. im building a single page app that uses the authorization code flow with pkce. everything works locally but fails in staging with a 401 bad request.

here is the code i use to generate the code_verifier and code_challenge:

import hashlib
import base64
import secrets

def generate_pkce():
 code_verifier = secrets.token_urlsafe(64)
 code_challenge = base64.urlsafe_b64encode(
 hashlib.sha256(code_verifier.encode('utf-8')).digest()
 ).decode('utf-8').replace('=', '')
 return code_verifier, code_challenge

verifier, challenge = generate_pkce()

i store the verifier in a session cookie. when i redirect to https://api.mypurecloud.com/oauth/authorize, i pass the challenge. after user consent, i get the code. then i post to /oauth/token with grant_type=authorization_code.

the error response is:
{"error":"invalid_grant","error_description":"PKCE verification failed"}

i checked the logs and the code_challenge sent matches what i computed. am i missing something about the encoding or is the verifier getting corrupted in the cookie? using python requests for the token exchange.

The documentation actually says PKCE verification fails when the client encoding does not match the server expectation.

Cause: Base64 padding (=) is stripped in urlsafe_b64encode but required by Genesys Cloud token endpoint.

Solution:

  1. Generate verifier: code_verifier = secrets.token_urlsafe(64)
  2. Generate challenge:
import base64
import hashlib

def get_code_challenge(code_verifier):
 digest = hashlib.sha256(code_verifier.encode('utf-8')).digest()
 return base64.urlsafe_b64encode(digest).decode('utf-8').replace('=', '')
  1. Pass both code_verifier and code_challenge exactly as generated.