Proof Key for Code Exchange (PKCE)

Overview

Proof Key for Code Exchange (PKCE) is a security mechanism specified in RFC 7636. It ensures that only you, the requester of the authorization code, can use the authorization code during Token Exchange.

PKCE works in tandem with client assertions and DPoP in order to prevent authorization code interception attacks, which is a type of attack where attackers gain access to the authorization code (e.g. via malware installed on the user's device) and use it to obtain a user's access token.

How To Implement PKCE

PKCE is used in two parts of the flow: the Pushed Authorization Request and the Token Exchange.

Authorization Request

PKCE requires you to send two additional parameters in the Pushed Authorization Request: the code_challenge and code_challenge_method.

You should follow the steps below to understand how to send these parameters.

1. Generate a code verifier

You should generate a high-entropy random string between 43-128 characters long, containing only alphanumeric characters, dashes, and underscores. This string must be different for every request.

Example code verifier

6I9tQd5tKn7Uy9ZfwEqd-YC71gSVfzcfVcyXLc34vQo

2. Generate a code challenge from the code verifier

The code challenge is generated by hashing the code verifier using the SHA-256 algorithm, then encoding the result using base64url encoding. Take note that base64url encoding is not the same as base64 encoding.

Example code challenge

hu0mAmPq8n91vRqudsGmriiG7blJDJS0bsDeOmEt17M

3. Send the code challenge and code challenge method in the Pushed Authorization Request

When you send the Pushed Authorization Request, you must include the code challenge generated in step 2 as the code_challenge parameter, and also send the code_challenge_method with the value of S256.

4. Store the code verifier in session storage

You must store the code verifier in your backend and associate it with the user's session, as you will need it later during Token Exchange.

Token Exchange

During token exchange, you must pass the code verifier that you had used to generate the code challenge for this authentication request as the code_verifier parameter in the request body. This serves as proof that you were the original generator of the code_challenge.

Last updated

Was this helpful?