PKCE и защита общедоступных клиентов
Узнайте, как расширение PKCE защищает поток кода авторизации OAuth2 в мобильных приложениях и одностраничных приложениях, которые не могут хранить секрет клиента
«PKCE и защита общедоступных клиентов» — бесплатный урок Spring Security 6 & JWT Authentication на CoddyKit. Это урок 4 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Spring Security 6 & JWT Authentication, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Spring Security 6 & JWT Authentication содержит 4 уроков всего.
Части этого урока еще не переведены и отображаются на английском.
The Public Client Problem
Mobile apps and SPAs are public clients: their code ships to the user, so they cannot safely store a client secret. Without a secret, the plain Authorization Code flow is vulnerable to interception.
What PKCE Solves
PKCE (Proof Key for Code Exchange, pronounced 'pixy') adds a dynamic secret per authorization request. Even if the authorization code is stolen, it cannot be exchanged without the matching proof.
The Code Verifier
The client generates a random, high-entropy string called the code_verifier and keeps it in memory for this one flow.
const codeVerifier = base64url(randomBytes(32));The Code Challenge
The client hashes the verifier with SHA-256 to make the code_challenge. The hash is sent to the server, but the original verifier never leaves the device yet.
const codeChallenge = base64url(sha256(codeVerifier));Starting the Authorization Request
The client sends the challenge and the method (S256) to the authorization endpoint along with the usual parameters.
GET /authorize?response_type=code
&client_id=app123
&code_challenge=XYZ...
&code_challenge_method=S256Server Stores the Challenge
The authorization server remembers the code_challenge and links it to the authorization code it issues after the user logs in.
Exchanging the Code
When swapping the code for tokens, the client now reveals the original code_verifier.
POST /token
grant_type=authorization_code
&code=abc123
&code_verifier=ORIGINAL_RANDOMServer Verifies the Proof
The server hashes the received verifier and compares it to the stored challenge. If they match, the requester is the same party that started the flow; otherwise it rejects the exchange.
if (sha256(received_verifier) !== stored_challenge) {
reject('invalid_grant');
}Why It Stops Interception
An attacker who steals the authorization code (for example via a malicious app on the device) still cannot use it: they never saw the code_verifier, which existed only inside the legitimate client's memory.
PKCE Is Now Recommended for All
Originally for mobile, PKCE is now recommended for every Authorization Code flow, including confidential web clients. OAuth 2.1 makes it the default.
Library Support
You rarely implement PKCE by hand. Libraries like AppAuth, oidc-client-ts, and Spring Authorization Server handle verifier generation, hashing, and validation for you.
Quick Check
Test your understanding of PKCE.
Recap
You learned how PKCE secures public clients:
- Public clients cannot keep a secret, so the plain code flow is unsafe
- The client creates a
code_verifierand sends its hash as thecode_challenge - The verifier is revealed only at token exchange
- A stolen code is useless without the verifier
PKCE is now the default for all Authorization Code flows.
Часто задаваемые вопросы
Урок «PKCE и защита общедоступных клиентов» бесплатный?
Да — полный текст урока «PKCE и защита общедоступных клиентов» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Spring Security 6 & JWT Authentication, подпишись на CoddyKit PRO. Курс Spring Security 6 & JWT Authentication содержит 4 уроков всего.
Чему я научусь в уроке «PKCE и защита общедоступных клиентов»?
Узнайте, как расширение PKCE защищает поток кода авторизации OAuth2 в мобильных приложениях и одностраничных приложениях, которые не могут хранить секрет клиента Ты практикуешь Spring Security 6 & JWT Authentication с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.
Нужен ли мне опыт, чтобы начать Spring Security 6 & JWT Authentication?
Предыдущий опыт не требуется. Spring Security 6 & JWT Authentication на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 4 из 4.
Сколько времени занимает урок «PKCE и защита общедоступных клиентов»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке Spring Security 6 & JWT Authentication?
Да. Каждый урок Spring Security 6 & JWT Authentication включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.
Все уроки этого курса
- Обзор протокола OAuth2
- Введение в OpenID Connect
- Распространённые типы разрешений OAuth2
- PKCE и защита общедоступных клиентов