# OAuth2授权码可通过客户端开放重定向被攻击者注入

- **ID:** `security/oauth2-authorization-code-injection-via-open-redirector`
- **领域:** security
- **类别:** auth_error
- **错误码:** `OAUTH2-CODE-INJECTION-001`
- **验证级别:** ai_generated
- **修复率:** 85%

## 根因

客户端应用程序允许开放重定向，攻击者可以利用它将窃取的授权码注入到重定向URI中，如果状态参数可预测或重用，则绕过状态参数检查。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| OAuth 2.0 RFC 6749 | active | — | — |
| Spring Security OAuth2 2.5.x | active | — | — |
| Microsoft Identity Platform v2.0 | active | — | — |

## 解决方案

1. ```
   在客户端实施严格的重定向URI验证：精确匹配已注册的URI，不允许通配符或部分匹配。Spring Security示例：`http.authorizeRequests().oauth2Login().authorizationEndpoint().authorizationRequestRepository(new HttpSessionOAuth2AuthorizationRequestRepository())`。
   ```
2. ```
   确保state参数是每个授权请求的加密随机且不可重用的值。Node.js示例：`const state = crypto.randomBytes(16).toString('hex');` 并将其存储在会话中供验证。
   ```
3. ```
   完全禁用客户端应用程序上的开放重定向功能。审计所有重定向端点，并将其删除或限制到允许的白名单中。
   ```

## 无效尝试

- **** — If the state is predictable (e.g., timestamp-based) or reused, an attacker can craft a valid redirect with a stolen code. (70% 失败率)
- **** — Wildcard patterns can be exploited to match attacker-controlled subdomains. (60% 失败率)
- **** — The client must validate the redirect_uri to prevent code injection via open redirectors. (90% 失败率)
