Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 51

OAuth 2.0 PKCE Flow for SPAs

Recommended resources

Welcome back. In our previous lessons, we've built a solid security perimeter for our frontend applications, architecting defenses against XSS, CSRF, and Clickjacking. We've focused on preventing an attacker from manipulating our application or tricking our users. Now, we shift our focus from pure defense to a core architectural responsibility: securely managing user identity and access delegation by integrating with external systems.

This is a frequent and critical topic in senior-level interviews. As an engineer who has integrated AWS Cognito, you've already implemented the patterns we're about to discuss. This lesson will formalize the theory behind those implementations, focusing on the "why" behind each step. We'll explore the OAuth 2.0 Authorization Code flow with Proof Key for Code Exchange (PKCE)—the modern gold standard for securing Single-Page Applications (SPAs). You will learn not just how it works, but why it is designed this way and the specific attacks it prevents.

1. Overview: The Problem of Delegated Authorization

Before OAuth 2.0, a common anti-pattern for an application (e.g., Yelp) to access a user's data from another service (e.g., Google Contacts) was to ask for the user's password directly. This is a massive security risk, as it grants the application carte blanche access and forces the user to share their most sensitive credential.

OAuth 2.0 was created to solve this problem of delegated authorization. It's a protocol that allows a user to grant a third-party application limited access to their resources on another service, without sharing their credentials.

To understand this, let's watch a segment from an excellent talk by OktaDev that frames this problem perfectly.

OAuth 2.0 and OpenID Connect (in plain English)

This video provides a clear, "plain English" explanation of OAuth's origins and purpose.

Watch the segment from the introduction of delegated authorization. The speaker uses the infamous Yelp example, which clearly illustrates the "password anti-pattern" that OAuth was designed to replace.

At its core, the OAuth 2.0 specification defines four key roles:

  • Resource Owner: The user who owns the data and can grant access.
  • Client: The application (your SPA) that wants to access the user's data.
  • Authorization Server: The server that authenticates the Resource Owner and issues access tokens (e.g., accounts.google.com).
  • Resource Server: The API server that hosts the protected resources (e.g., the Google Calendar API).

The entire goal of an OAuth flow is for the Client to obtain an Access Token, which is a credential it can present to the Resource Server to prove it has permission to access the Resource Owner's data.


2. Core Concepts: The Authorization Code Flow

The most secure and common OAuth 2.0 flow is the Authorization Code flow. Originally designed for traditional web applications with a backend, it cleverly separates communication channels to protect sensitive data.

This separation relies on the distinction between a front channel and a back channel:

  • Front Channel: Communication happens through the user's browser via redirects. This channel is considered less secure because data in the URL is visible, and the browser environment can be compromised (e.g., by malicious extensions).
  • Back Channel: Direct, server-to-server communication. This channel is highly secure because it happens outside the user's browser, and servers can use secrets that are never exposed to the client.

The following video segment explains this critical distinction and walks through the traditional Authorization Code flow.

OAuth 2.0 and OpenID Connect (in plain English)

This part of the OktaDev talk is essential for understanding the fundamental security design of the Authorization Code flow.

First, watch the explanation of front vs. back channels. This concept is the key to understanding why the flow has an extra exchange step. Then, review the walkthrough of the Authorization Code flow itself, which details how the authorization_code is exchanged for an access_token. Finally, see how the access_token is used in a token exchange and API call.

To summarize the traditional flow for a server-side app:

  1. Front Channel: The user is redirected from the Client to the Authorization Server.
  2. Front Channel: The user logs in, consents, and is redirected back to the Client with a short-lived authorization_code in the URL.
  3. Back Channel: The Client's backend server takes this authorization_code and sends it back to the Authorization Server, along with a client_secret (a password for the application itself).
  4. Back Channel: The Authorization Server verifies the code and the secret, then returns an access_token to the Client's backend.

This is secure because the powerful access_token is never exposed to the browser (front channel).

The Security Gap for SPAs

This flow presents a major problem for SPAs. An SPA is a public client—its entire source code is downloaded and executed in the browser. There is no secure place to store a client_secret. If you embed it in your JavaScript bundle, an attacker can easily extract it.

Without a client_secret, an attacker who intercepts the authorization_code from the browser redirect (e.g., through a malicious browser extension, or if the redirect is compromised) can exchange it for an access_token themselves. This is known as an Authorization Code Interception Attack.

This is where PKCE comes in.


3. Deep Dive: The Authorization Code Flow with PKCE

PKCE (Proof Key for Code Exchange), pronounced "pixie," is an extension to the Authorization Code flow that secures public clients. It eliminates the need for a static client_secret by using a dynamically generated secret for each authorization request.

The core idea is to prove that the client instance that starts the authorization flow is the same one that finishes it.

Here’s how it works:

  1. Generate Secrets: Before starting, the SPA generates two values:

    • code_verifier: A long, random, cryptographically-secure string. This is the "proof key" and is kept secret within the SPA's memory.
    • code_challenge: A SHA-256 hash of the code_verifier.
  2. Initiate Flow: The SPA redirects the user to the Authorization Server, but this time it includes the code_challenge and the hashing method (code_challenge_method: 'S256').

  3. User Authenticates: The user logs in and grants consent as usual. The Authorization Server stores the code_challenge associated with this flow.

  4. Receive Code: The Authorization Server redirects the user back to the SPA with an authorization_code.

  5. Exchange Code with Proof: The SPA sends a request to the Authorization Server's token endpoint containing the authorization_code it just received AND the secret code_verifier from step 1.

  6. Server Verifies Proof: The Authorization Server performs the same SHA-256 hash on the received code_verifier. It then compares the result with the code_challenge it stored in step 3.

    • If they match: The server knows the request is legitimate and issues an access_token.
    • If they don't match: The request is rejected.

This flow is visually summarized in the diagrams below.

A detailed 15-step diagram showing the interactions between the User, Browser, Client, Security Token Service (Authorization Server), and API in a PKCE flow.
This diagram simplifies the PKCE flow, clearly distinguishing between the front channel (orange lines through the browser) and the back channel (green lines directly between application components).

The ByteMonk video below provides a very crisp, step-by-step walkthrough of this exact process.

OAuth is Broken Without This | Meet PKCE

This video focuses specifically on PKCE, explaining the vulnerability it solves and how it works with clear steps and a great code example.

First, watch the segment on the traditional flow's vulnerability for public clients. Then, follow the detailed step-by-step PKCE explanation. Finally, see how this translates into a JavaScript code example to solidify your understanding of the implementation.

For a detailed text-based explanation and code snippets you can refer to, the following article is an excellent resource.

Frontend System Design: Authentication Flows -- Guide - DEV Community

This guide provides a comprehensive breakdown of the PKCE flow with code examples.

Start by reading the section explaining why PKCE is necessary for SPAs. Then, study the step-by-step diagram and explanation of how PKCE works. Finally, review the code snippets for generating the PKCE pair and for the two main steps: starting the flow and handling the callback to exchange the code.

Because of PKCE, an attacker who intercepts the authorization_code is thwarted. They can't exchange it for an access_token because they do not possess the secret code_verifier.


4. Trade-Off Analysis: OAuth 2.0 Grant Types

The Authorization Code flow with PKCE is the recommended approach for SPAs, but OAuth 2.0 defines several grant types, each suited for different scenarios. Understanding their trade-offs is crucial for senior-level design discussions.

Grant Type Use Case Client Type Security Profile Key Characteristic
Authorization Code + PKCE SPAs, Mobile Apps, Desktop Apps Public High The modern standard. Requires dynamic proof (code_verifier) to exchange the authorization_code. access_token is retrieved via a direct POST, not a redirect.
Authorization Code Traditional Web Apps with a Backend Confidential High The classic secure flow. Requires a static client_secret on the back-channel to exchange the authorization_code. access_token is never exposed to the browser.
Implicit Flow (Deprecated) Legacy SPAs Public Low The access_token is returned directly in the URL fragment after the redirect. Highly susceptible to token leakage and interception. Should not be used for new applications.
Client Credentials Machine-to-Machine (M2M) Confidential High No user involved. The client authenticates itself directly with its client_id and client_secret to get an access_token to call another service.
Resource Owner Password (Deprecated) Highly-trusted first-party apps (e.g., official mobile app) Confidential Medium User provides their username/password directly to the client application, which exchanges it for an access_token. Bypasses the redirect flow but requires extreme trust in the client.

5. Design Challenge

Scenario: You are the lead frontend architect for "TaskMaster," a new collaborative project management SPA built with React. You need to implement "Login with GitHub" functionality.

Task: Design the authentication flow.

  1. Explain why you would not use the Implicit Flow.
  2. Your application is a pure SPA, served from a CDN with no traditional backend server of its own. Explain why the standard Authorization Code Flow (without PKCE) is architecturally insecure for this setup.
  3. Draw a sequence diagram outlining the complete Authorization Code + PKCE flow. Label each arrow with the key parameters being passed (e.g., client_id, redirect_uri, code_challenge, code_verifier, authorization_code, access_token).
  4. After successfully obtaining an access_token, where would you store it in the browser? Discuss the security trade-offs of localStorage vs. an in-memory JavaScript variable.

6. Senior-Level Insight

A mid-level engineer can correctly describe the PKCE flow. A senior or staff-level engineer situates this flow within the broader landscape of identity protocols. They will immediately distinguish between OAuth 2.0 (Authorization) and OpenID Connect (OIDC) (Authentication).

  • OAuth 2.0 provides an access_token that answers the question: What can this app do on my behalf?
  • OIDC is a thin layer on top of OAuth 2.0. By adding the openid scope to the request, you receive an additional id_token alongside the access_token. The id_token is a JWT (JSON Web Token) that answers the question: Who is the user that just logged in? It contains claims like the user's email, name, and a unique subject identifier.

In an interview, a senior candidate would state: "For a 'Login with Google' feature, we'll use the OIDC protocol, which leverages the OAuth 2.0 Authorization Code flow with PKCE. This gives us both an id_token to authenticate the user in our SPA and an access_token to authorize calls to Google APIs if needed." They would also advocate for using PKCE even for confidential clients, as it provides defense-in-depth against code injection and is required by the upcoming OAuth 2.1 standard.


7. Common Mistakes in Interviews

  • Recommending the Implicit Flow: This is an immediate red flag, indicating outdated knowledge. It has been officially deprecated in favor of Auth Code + PKCE.
  • Confusing Authorization and Authentication: Stating that OAuth is for "logging users in" without mentioning OIDC is a common simplification. Be precise.
  • Failing to Explain Why SPAs are Public Clients: Simply saying "SPAs can't store secrets" is okay. Explaining why (source code is public, no secure server-side storage) demonstrates deeper understanding.
  • Mixing up code_verifier and code_challenge: Incorrectly describing which one is hashed and which one is sent when. Remember: you send the challenge first, and provide the verifier as proof later.
  • Poor Token Storage Strategy: Suggesting localStorage for access tokens without immediately discussing the XSS risk and mitigation strategies.

8. Quiz

  1. What is the primary vulnerability that PKCE is designed to prevent for public clients?
    a) Cross-Site Scripting (XSS)
    b) Authorization Code Interception
    c) Cross-Site Request Forgery (CSRF)
    d) Clickjacking

  2. In the PKCE flow, what is the code_challenge?
    a) A random string sent to the authorization server to be exchanged for a token.
    b) A secret password for the client application.
    c) A hashed version of the code_verifier.
    d) The access_token itself.

  3. Why is a Single-Page Application (SPA) considered a "public client" in OAuth 2.0 terminology?
    a) Because it is accessible to the public on the internet.
    b) Because it doesn't have a secure backend environment to store a client_secret.
    c) Because it can only use public APIs.
    d) Because its source code is open source.

  4. During the PKCE token exchange, which of the following is sent to the authorization server to prove the client's identity?
    a) The client_secret
    b) The code_challenge
    c) The code_verifier
    d) The id_token

  5. Open-ended: Imagine a malicious browser extension is running on a user's machine. It successfully intercepts the authorization_code from a URL redirect during a login flow for an SPA that correctly uses PKCE. Explain, step-by-step, why the extension will fail to acquire an access_token.



Conclusion

You now have a deep, architectural understanding of the modern standard for securing SPAs and mobile applications. You can not only implement the Authorization Code flow with PKCE but also articulate the security principles that underpin its design, the vulnerabilities it mitigates, and its place in the larger identity ecosystem. This level of detail is precisely what interviewers at top-tier companies are looking for.

Key Takeaways:

  • OAuth 2.0 is for Authorization: It's about delegating permissions, not just logging in.
  • SPAs are Public Clients: They cannot securely store a static client_secret.
  • PKCE Prevents Code Interception: It uses a dynamic, one-time proof (code_verifier/code_challenge) to secure the flow.
  • Auth Code + PKCE is the Standard: It has replaced the insecure Implicit flow for all modern public clients.

In our next lesson, we will build directly on this topic by diving into token storage trade-offs. We'll rigorously evaluate the pros and cons of storing tokens in localStorage vs. httpOnly cookies vs. in-memory, a crucial follow-up question in any authentication design interview.