# 缺少PKCE导致的OAuth2授权码注入

- **ID:** `security/oauth2-authorization-code-injection-via-missing-pkce`
- **领域:** security
- **类别:** auth_error
- **错误码:** `OAUTH2_MISSING_PKCE`
- **验证级别:** ai_generated
- **修复率:** 85%

## 根因

没有使用PKCE（代码交换证明密钥）的OAuth2授权码流程允许攻击者拦截授权码并交换令牌，绕过预期的客户端。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| OAuth2.0 | active | — | — |
| Spring Security 5.7+ | active | — | — |
| Okta 2023.04.0 | active | — | — |
| Auth0 2023.01 | active | — | — |

## 解决方案

1. ```
   Implement PKCE in the authorization request by generating a code_verifier (random string) and its SHA-256 hash as code_challenge, then send code_challenge_method=S256. Example in JavaScript: const codeVerifier = crypto.randomBytes(32).toString('base64url'); const codeChallenge = crypto.createHash('sha256').update(codeVerifier).digest('base64url'); Then include code_challenge and code_challenge_method in the authorization request, and send code_verifier in the token request.
   ```
2. ```
   Enable PKCE enforcement on the authorization server (e.g., in Auth0 tenant settings under 'Advanced OAuth' > 'OIDC Conformant').
   ```
3. ```
   Upgrade to OAuth2 libraries that enforce PKCE by default (e.g., Spring Security 5.7+ with oauth2Login).
   ```

## 无效尝试

- **** — Enabling HTTPS only protects the transport layer; the authorization code can still be intercepted via malicious redirects or browser extensions, as PKCE is a separate mechanism. (60% 失败率)
- **** — Using state parameter alone is insufficient because if the attacker can predict or steal the state, they can still inject the code; PKCE uses a cryptographically random code verifier that cannot be guessed. (70% 失败率)
- **** — Shortening the authorization code lifetime reduces the window for attack but does not prevent injection; PKCE is the only standard mitigation. (50% 失败率)
