# OAuth2授权码交换失败：需要PKCE code_verifier但未提供

- **ID:** `security/oauth2-pkce-code-verifier-missing`
- **领域:** security
- **类别:** protocol_error
- **错误码:** `OAUTH2_PKCE_MISSING`
- **验证级别:** ai_generated
- **修复率:** 90%

## 根因

授权服务器要求令牌交换时使用PKCE（代码交换证明密钥），但客户端未发送'code_verifier'参数，通常是因为客户端库或配置不支持PKCE。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| Spring Security OAuth2 5.8.0 | active | — | — |
| oauthlib 3.2.2 | active | — | — |
| oidc-client-ts 2.2.0 | active | — | — |
| IdentityServer4 4.1.2 | active | — | — |

## 解决方案

1. ```
   每次授权请求生成一个随机的'code_verifier'并存储在会话中。例如，在Python中：`import secrets; code_verifier = secrets.token_urlsafe(64)`。然后在令牌交换时发送它。
   ```
2. ```
   使用默认支持PKCE的现代OAuth2客户端库，例如Python的`oauthlib`或JavaScript的`oidc-client-ts`。配置以启用PKCE。
   ```
3. ```
   如果使用自定义实现，确保授权请求中包含'code_challenge'和'code_challenge_method'，并在令牌请求中发送'code_verifier'。
   ```

## 无效尝试

- **** — Sending a static 'code_verifier' value for all users makes the PKCE challenge predictable, allowing an attacker to intercept the authorization code and use the known verifier to exchange it. (70% 失败率)
- **** — Disabling PKCE enforcement on the authorization server reduces security and may not be possible if the server is managed by a third party. (50% 失败率)
- **** — Reusing the same 'code_verifier' across multiple authorization requests can lead to replay attacks and is against the PKCE specification. (60% 失败率)
