# OAuth2 错误：授权码缺少 PKCE 挑战

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

## 根因

授权码请求未包含 code_challenge 参数，但授权服务器要求所有公共客户端使用 PKCE。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| OAuth2 RFC 7636 | active | — | — |
| Spring Security 6.1+ | active | — | — |
| Keycloak 22+ | active | — | — |
| Auth0 2023+ | active | — | — |
| Okta 2023+ | active | — | — |

## 解决方案

1. ```
   Generate a code_verifier (random 43-128 chars) and its SHA-256 hash as code_challenge during the authorization request. Example in Python:
import hashlib, base64, secrets
code_verifier = secrets.token_urlsafe(64)
code_challenge = base64.urlsafe_b64encode(hashlib.sha256(code_verifier.encode()).digest()).rstrip(b'=').decode()
Then include code_challenge=SHA256_hash and code_challenge_method=S256 in the authorization URL.
   ```
2. ```
   If using a library like `requests-oauthlib`, enable PKCE by setting `include_pkce=True` in the OAuth2 session initialization.
   ```

## 无效尝试

- **** — PKCE is a separate security extension; scopes are unrelated. (70% 失败率)
- **** — If the client is public, the server still enforces PKCE regardless of client_secret. (50% 失败率)
- **** — Most providers enforce PKCE by default and do not allow disabling. (30% 失败率)
