DEV Community

Cover image for What is PKCE?
Klee Thomas
Klee Thomas

Posted on

What is PKCE?

PKCE or Proof Key Code Exchange (often pronounced "Pixie") is an acronym you may have seen around when looking into how to authenticate users in modern web apps.

So what is PKCE?
PKCE is an extension to the Authorization Code Flow grant that is part of the OAuth 2.0 spec. The problem that PKCE solves is that native mobile applications and Single Page web apps are not able to securely store a client secret in order to prove it's identity.

What problem are we solving by ensuring that a client can prove it's identity?
The problem is with the way that Authorization Code Flow works. It works by:

  1. The Client Application redirecting the user to the Authentication Server
  2. The user logs into the Authentication Server
  3. The user is redirected back to the Client Application with a code as a query parameter
  4. The Client Application sending a POST request to the Authentication Server with the code.
  5. The Authentication Server responding with an Identity Token an optionally an Access Token and Refresh Token.

So where is the problem?
The problem is that anyone who gets the code from that query string can exchange it for tokens.

And how does PKCE address this?
PKCE adds an extra parameter into both the initial redirect and the code exchange POST request. This request takes the form of a challenge in the initial call and a verifier in the subsequent one. The verifier is a string of randomly generated characters. The challenge is a SHA 256 hash (Base64 Url Encoded) of the verifier. The Authorization Server receives the challenge with the initial login request and stores the challenge along side the code. When the request comes in to exchange that code the for a token the original verifier string must be sent along with the request. The Authorization Server then performs the same hashing function on the verifier that has been passed by the client. If the generated hash matches then the challenge sent in the initial request server returns the tokens, otherwise the request is rejected.

This means that by using PKCE the client provides a Key that can be used as Proof that it was the requester of the authentication during the Code Exchange.

How do you implement PKCE?
I plan to post a follow up to this with code examples of how to implement the client side of of PKCE. That is really just for anyone who is interested in how it works under the hood.
The reality, like anything in Identity and Security, you should use a library to take care of it for you. Auth0 provide fantastic and easy to use libraries that are known to work.

Oldest comments (0)