How to generate a PKCE code challenge with PHP ?

Julien Balmont
Zenchef’s Tech and Product Blog
2 min readOct 15, 2019

--

When you do not use the right functions, PKCE (Proof Key for Code Exchange) can sometimes be a real pain and can result in OAUTH2 attempts to get a token returning a “invalid code verifier passed”.

Why is it a pain ? because PHP doesn’t provide a version of the BASE64URL SAFE ENCODING, replying to the RFC4648

To generate a code challenge using PHP, follow those simple steps :

  1. First, generate an ASCII code verifier, matching the RegExp :
[A-Za-z0-9-._~]{43,128}

This code verifier has to be saved to be compared in the end of the process.

For example, let’s use

$code_verifier = '--6t5HeyDNhPx8C9MYOEFWAgj9q9Ijhg7at-WtGGmrgIVB';

2. Then, let’s start the code challenge generation. First step is SHA-256 encoding of the code verifier.

$hash = hash('sha256', $code_verifier)

This should return the hash

c006061843c7a4685a1b58194e6c89f0cd4bcbb2651aea14556041549e0ec535

3. Last step is where PHP built in base64url_encode function fails. We’ll do a workaround using base64url_encode and pack function.

$code_challenge = base64url_encode(pack('H*', $hash));

4. You now have a correct code challenge you can use to get an OAUTH2 access token

wAYGGEPHpGhaG1gZTmyJ8M1Ly7JlGuoUVWBBVJ4OxTU

Yeepee !

More resources :

You can generate or test your code challenges here : https://tonyxu-io.github.io/pkce-generator/

All the explanations and documentations of PKCE are listed here : https://oauth.net/2/pkce/

--

--