공개 클라이언트를 위한 PKCE
코드 교환을 위한 증명 키(PKCE)와 이를 통해 모바일 앱과 같은 공개 클라이언트를 권한 부여 코드 가로채기 공격으로부터 보호하는 방법을 알아보세요.
공개 클라이언트를 위한 PKCE은(는) CoddyKit의 무료 OAuth2 & OpenID Connect Deep Dive 강의입니다. 이것은 4개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 OAuth2 & OpenID Connect Deep Dive 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. OAuth2 & OpenID Connect Deep Dive 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
Public Clients & No Secrets
Imagine a mobile app or a Single-Page Application (SPA) running in a browser. These are known as public clients in OAuth2.
- They run on devices or environments that can't reliably keep a secret.
- Unlike a server-side application, they can't securely store a client secret.
This lack of a secret creates a security challenge, making them vulnerable to certain attacks.
Authorization Code Interception
Without a client secret, public clients face a specific risk: the Authorization Code Interception Attack.
- An attacker might intercept the authorization code sent back to your app.
- If they get the code, and there's no client secret to verify, they could exchange it for an access token.
This means an attacker could gain access to a user's resources, impersonating your application.
PKCE: Protecting Public Clients
To protect public clients from interception attacks, OAuth2 introduced Proof Key for Code Exchange (PKCE), pronounced "pixy."
- PKCE adds a dynamic secret to the authorization code flow.
- This secret is created by the client for each authorization request.
Even if an attacker intercepts the authorization code, they won't have this secret, preventing them from exchanging the code for tokens.
Code Verifier: The Client's Secret
At the heart of PKCE is the code_verifier. It's a cryptographically random string generated by the client application for each authorization attempt.
- It's a high-entropy secret, meaning it's long and hard to guess.
- The client keeps this
code_verifierprivate and never sends it directly to the authorization endpoint.
Think of it as a one-time password your app generates and remembers.
Code Challenge: The Public Proof
Instead of sending the code_verifier, the client sends a code_challenge to the authorization server.
- The
code_challengeis a transformed version of thecode_verifier. - The transformation method (e.g., SHA256 hash then Base64Url encode) is specified by
code_challenge_method.
This allows the authorization server to verify the client later without ever knowing the actual code_verifier upfront.
PKCE Flow: Auth Request
Let's trace the PKCE flow. First, the public client (your app) prepares for authorization:
- It generates a unique
code_verifier. - It transforms this into a
code_challengeusing S256 (SHA256 hash + Base64Url encoding). - It then sends an authorization request to the Authorization Server, including the
code_challengeandcode_challenge_method.
Example parameters: code_challenge=xyz&code_challenge_method=S256
PKCE Flow: Auth Code Grant
Upon receiving the authorization request with the code_challenge:
- The Authorization Server stores the received
code_challengeand its method. - It authenticates the user and obtains their consent.
- It then redirects the user back to the client's registered redirect URI, providing an authorization code.
At this point, the client still holds its code_verifier locally.
PKCE Flow: Token Request
Now, with the authorization code in hand, the client needs to exchange it for an access token:
- The client makes a POST request to the Authorization Server's token endpoint.
- This request includes the authorization code AND the original
code_verifierit generated earlier.
This is where the magic happens! The code_verifier acts as proof that this client is the legitimate one.
PKCE Flow: Verification & Tokens
When the Authorization Server receives the token request with the code_verifier:
- It recalculates the
code_challengeusing the providedcode_verifierand the storedcode_challenge_method. - It compares this newly calculated challenge with the
code_challengeit stored in Step 1. - If they match, the client is verified, and the Authorization Server issues access and refresh tokens. Otherwise, the request is denied.
Generating Verifier & Challenge
Here's a simple Java example demonstrating how to generate a code_verifier and its corresponding code_challenge using the S256 method. This is a core part of PKCE implementation.
Try running the code to see the generated values!
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Base64;
public class Main {
public static void main(String[] args) throws NoSuchAlgorithmException {
// 1. Generate a secure random code_verifier
SecureRandom sr = new SecureRandom();
byte[] codeVerifierBytes = new byte[32]; // 32 bytes = 256 bits
sr.nextBytes(codeVerifierBytes);
String codeVerifier = Base64.getUrlEncoder().withoutPadding().encodeToString(codeVerifierBytes);
// 2. Derive the code_challenge using S256 (SHA256 + Base64Url-encode)
MessageDigest md = MessageDigest.getInstance("SHA-256");
byte[] digest = md.digest(codeVerifier.getBytes(java.nio.charset.StandardCharsets.US_ASCII));
String codeChallenge = Base64.getUrlEncoder().withoutPadding().encodeToString(digest);
System.out.println("Code Verifier: " + codeVerifier);
System.out.println("Code Challenge: " + codeChallenge);
System.out.println("Method: S256");
}
}PKCE Quick Check
PKCE adds a vital layer of security for public clients. Which of the following best describes the primary problem PKCE solves?
Recap: PKCE's Security Layer
We've learned about PKCE, a crucial security extension for OAuth2, especially for public clients like mobile apps and SPAs.
- Public clients can't securely store client secrets.
- PKCE uses a one-time
code_verifierand its transformedcode_challengeto verify the legitimate client. - This protects against Authorization Code Interception attacks, ensuring only the intended client can exchange the authorization code for tokens.
PKCE makes OAuth2 flows much more secure for applications that operate in less trusted environments.
자주 묻는 질문
“공개 클라이언트를 위한 PKCE” 강의는 무료인가요?
네 — “공개 클라이언트를 위한 PKCE” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 OAuth2 & OpenID Connect Deep Dive 강의 전체를 잠금 해제할 수 있습니다. OAuth2 & OpenID Connect Deep Dive 강의에는 총 4개의 강의가 포함되어 있습니다.
“공개 클라이언트를 위한 PKCE”에서 뭘 배우나요?
코드 교환을 위한 증명 키(PKCE)와 이를 통해 모바일 앱과 같은 공개 클라이언트를 권한 부여 코드 가로채기 공격으로부터 보호하는 방법을 알아보세요. 브라우저에서 직접 실행하는 실습 코드로 OAuth2 & OpenID Connect Deep Dive을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
OAuth2 & OpenID Connect Deep Dive을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 OAuth2 & OpenID Connect Deep Dive은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 1번째 강의입니다.
“공개 클라이언트를 위한 PKCE” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 OAuth2 & OpenID Connect Deep Dive 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 OAuth2 & OpenID Connect Deep Dive 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- 공개 클라이언트를 위한 PKCE
- 갱신 토큰 및 범위
- 리소스 소유자 비밀번호 자격 증명
- 토큰 교환(RFC 8693)