# OAuth2授权码注入：缺少state参数导致跨站请求伪造

- **ID:** `security/oauth2-state-parameter-missing`
- **领域:** security
- **类别:** auth_error
- **错误码:** `CSRF_TOKEN_MISSING`
- **验证级别:** ai_generated
- **修复率:** 92%

## 根因

OAuth2客户端未生成或验证加密随机的state参数，使攻击者可以将自己的授权码注入到受害者的会话中。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| OAuth2 2.0 RFC 6749 | active | — | — |
| Passport.js 0.6.0 | active | — | — |
| OmniAuth 2.1.0 | active | — | — |

## 解决方案

1. ```
   Generate a cryptographically random state value per request, store it in the user session, and validate it on callback. Example in Node.js: const state = crypto.randomBytes(16).toString('hex'); req.session.oauthState = state; res.redirect(authUrl + '&state=' + state);
   ```
2. ```
   Use PKCE (Proof Key for Code Exchange) with S256 challenge method, which inherently binds the authorization code to the client session
   ```
3. ```
   Enforce state parameter validation at the authorization server level by rejecting requests without a valid nonce
   ```

## 无效尝试

- **** — Static state is predictable and does not prevent CSRF; attacker can guess or reuse it. (95% 失败率)
- **** — Cookie-only state can be stolen via XSS or reused across sessions. (70% 失败率)
- **** — Redirect_uri matching does not prevent CSRF; attacker can still inject code via a pre-registered URI. (85% 失败率)
