It's all about SECURITY

PKCE - Proof Key Exchange Code - OAuth Extension


I want to discuss an interesting security concept in OAuth 2.0 called PKCE (Proof Key for Code Exchange).

If you have worked with OAuth 2.0, you are probably familiar with the Authorization Code Flow. But have you ever thought about what could happen if someone intercepts the authorization code before it gets exchanged for an access token?


This is one of the security challenges that PKCE addresses. Let me try to explain this with a simple example.


What is PKCE and when should we use it?

PKCE is a security extension to OAuth 2.0 that helps protect the Authorization Code Flow from authorization code interception attacks.

Let's say we have a mobile application or a Single Page Application (SPA), such as a React or Angular application, and we want to implement authentication using an Identity Provider.

Unlike traditional server-side applications, these applications cannot securely store a client secret because these apps do not have a backend. If we store client secret at the client side, it can be extracted easily. 

Now, imagine an attacker intercepts the authorization code during the login process. If the attacker can exchange that code for an access token, they may gain unauthorized access to protected resources.


So, how do we prevent this?


This is where PKCE comes into the picture.


How does PKCE work?

PKCE introduces two important values: Code Verifier and Code Challenge.

Let's understand the flow:


  1. When the user initiates the login process, the application generates a random string called the Code Verifier.
  2. The application then generates a Code Challenge (Hash value of code verifier) using the Code Verifier and the SHA-256 hashing algorithm
  3. The application sends this Code Challenge to the Identity Provider as part of the authorization request.
  4. Once the user successfully authenticates, the Identity Provider redirects the user back to the application with an Authorization Code.
  5. The application sends the Authorization Code along with the original Code Verifier to the token endpoint. [Remember this as it is sending the code verifier which is not the hash value]
  6. The Identity Provider validates the Code Verifier against the previously received Code Challenge. If both match, the access token is issued; otherwise, the request is rejected.


So, what happens if an attacker intercepts the Authorization Code?

The attacker may have the authorization code, but they don't have the original Code Verifier. Therefore, they cannot successfully exchange the authorization code for an access token.

That's the whole idea behind PKCE