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:
- Front Channel: The user is redirected from the Client to the Authorization Server.
- Front Channel: The user logs in, consents, and is redirected back to the Client with a short-lived
authorization_codein the URL. - Back Channel: The Client's backend server takes this
authorization_codeand sends it back to the Authorization Server, along with aclient_secret(a password for the application itself). - Back Channel: The Authorization Server verifies the code and the secret, then returns an
access_tokento 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:
-
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: ASHA-256hash of thecode_verifier.
-
Initiate Flow: The SPA redirects the user to the Authorization Server, but this time it includes the
code_challengeand the hashing method (code_challenge_method: 'S256'). -
User Authenticates: The user logs in and grants consent as usual. The Authorization Server stores the
code_challengeassociated with this flow. -
Receive Code: The Authorization Server redirects the user back to the SPA with an
authorization_code. -
Exchange Code with Proof: The SPA sends a request to the Authorization Server's token endpoint containing the
authorization_codeit just received AND the secretcode_verifierfrom step 1. -
Server Verifies Proof: The Authorization Server performs the same SHA-256 hash on the received
code_verifier. It then compares the result with thecode_challengeit 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.
- If they match: The server knows the request is legitimate and issues an
This flow is visually summarized in the diagrams below.


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.
- Explain why you would not use the Implicit Flow.
- 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.
- 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). - After successfully obtaining an
access_token, where would you store it in the browser? Discuss the security trade-offs oflocalStoragevs. 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_tokenthat 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
openidscope to the request, you receive an additionalid_tokenalongside theaccess_token. Theid_tokenis 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_verifierandcode_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
localStoragefor access tokens without immediately discussing the XSS risk and mitigation strategies.
8. Quiz
-
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 -
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 thecode_verifier.
d) Theaccess_tokenitself. -
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 aclient_secret.
c) Because it can only use public APIs.
d) Because its source code is open source. -
During the PKCE token exchange, which of the following is sent to the authorization server to prove the client's identity?
a) Theclient_secret
b) Thecode_challenge
c) Thecode_verifier
d) Theid_token -
Open-ended: Imagine a malicious browser extension is running on a user's machine. It successfully intercepts the
authorization_codefrom 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 anaccess_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.