# OAuth2授权码重用检测到：同一授权码被多次使用

- **ID:** `security/oauth2-authorization-code-reuse-detection`
- **领域:** security
- **类别:** auth_error
- **错误码:** `invalid_grant`
- **验证级别:** ai_generated
- **修复率:** 90%

## 根因

授权服务器未能正确标记授权码在首次使用后已消耗，允许攻击者重放之前截获的授权码以获取新的访问令牌。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| Spring Security OAuth2 2.5.0 | active | — | — |
| Keycloak 21.0.0 | active | — | — |
| Okta 2024.02.0 | active | — | — |

## 解决方案

1. ```
   Ensure the authorization server marks the code as consumed atomically upon first use. For example, in a database-backed implementation, use a transaction: UPDATE auth_codes SET consumed=true WHERE code=? AND consumed=false. If affected rows is 0, reject the request.
   ```
2. ```
   Implement a one-time use token pattern: after issuing the access token, immediately invalidate the authorization code from the store (e.g., Redis: DEL auth_code:<code>).
   ```
3. ```
   Add a nonce or state parameter that must be unique per authorization request and validated during token exchange, preventing replay even if the code is intercepted.
   ```

## 无效尝试

- **** — Longer expiration times actually increase the window for replay attacks, making the problem worse. (80% 失败率)
- **** — Authorization codes are randomly generated and not meant to be guessed; the issue is replay, not brute force. (50% 失败率)
- **** — Manual review is not scalable and cannot prevent real-time attacks; automated detection must be implemented. (70% 失败率)
