# OAuth2 state参数重用允许通过重放攻击进行CSRF

- **ID:** `security/oauth2-state-parameter-replay-attack`
- **领域:** security
- **类别:** auth_error
- **验证级别:** ai_generated
- **修复率:** 88%

## 根因

当OAuth2 state参数未绑定到特定用户会话或跨多个授权请求重用时，攻击者可以重放捕获的授权响应，将受害者的账户绑定到攻击者的会话。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| OAuth2 2.0 | active | — | — |
| Spring Security OAuth2 5.8.0 | active | — | — |
| Passport.js 0.7.0 | active | — | — |

## 解决方案

1. ```
   每次授权请求生成加密随机的state参数，存储在用户会话中，并在回调时验证。Node.js示例：const state = crypto.randomBytes(16).toString('hex'); req.session.oauthState = state; res.redirect(`https://provider/authorize?response_type=code&client_id=...&state=${state}`);
   ```
2. ```
   使用类似nonce的机制，state包含时间戳和用户ID，并用服务器密钥签名，以防止重放。
   ```

## 无效尝试

- **Using a static state value for all users** — A static state is predictable and can be easily forged by an attacker; it doesn't provide CSRF protection. (100% 失败率)
- **Generating state but not storing it in the session** — Without session binding, the state cannot be verified on callback; any state value is accepted, enabling replay. (95% 失败率)
