PKCE – Proof Key for Code Exchange

Banner for Learning Computers post

Securing OAuth 2.0 for the Modern Web

In the world of Information Security, acronyms often act as gatekeepers to critical concepts. One of the most vital for modern identity management is PKCE (pronounced “pixie”), which stands for Proof Key for Code Exchange.  If you are new to the field, you likely know that OAuth 2.0 is the industry standard for authorizations what allows you to “Sign in with Google” on a third-party app without giving that app your password.  However, the original OAuth 2.0 design had a security gap, particularly for mobile and single-page applications (SPAs).  PKCE was designed to bridge that gap.

The Problem: Authorization Code Interception

In a standard OAuth flow, the application receives an Authorization Code from the login server. The application then swaps this code for an Access Token.  The risk? On a mobile device or a browser, other malicious apps or scripts can sometimes “sniff” or intercept that initial Authorization Code. If an attacker gets the code, they can trade it for a token and hijack the user’s session.

The Solution: How PKCE Works

Computer Post ImagePKCE adds a dynamic, one-time secret to the process, ensuring that the entity requesting the token is the exact same entity that started the login process. It follows a simple three-step dance:

  1. The Secret Creation: Before the login starts, your app creates a random string called a Code Verifier. It then hashes this string (usually using SHA-256) to create a Code Challenge.
  2. The Initial Request: When the app sends the user to log in, it attaches the Code Challenge. The server tucks this away for later.
  3. The Verification: Once the user logs in and the app receives the Authorization Code, it sends that code back to the server to get a token. This time, it also sends the original, unhashed Code Verifier.
  4. The “Aha!” Moment: The server hashes the Verifier provided in step three. If it matches the Challenge provided in step one, the server knows the request is legitimate. An attacker who intercepted the code in the middle would not have the original secret (the Verifier) and therefore cannot get a token.

Why It Matters

Originally, PKCE was an extension for mobile apps, but it is now considered best practice for all OAuth 2.0 clients, including traditional web apps. Remember: if you are implementing OAuth, you should be using PKCE by default to prevent “Authorization Code Interception” attacks.

Further Reading & Citations