# CSRF 令牌未绑定到用户会话

- **ID:** `security/csrf-token-not-bound-to-session`
- **领域:** security
- **类别:** auth_error
- **错误码:** `CSRFValidationException`
- **验证级别:** ai_generated
- **修复率:** 90%

## 根因

CSRF 令牌是全局生成或按请求生成的，但未与会话绑定，允许攻击者跨会话预测或重用令牌。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| Django 4.2 | active | — | — |
| Spring Security 5.7 | active | — | — |
| Flask-WTF 1.1 | active | — | — |
| Express.js | active | — | — |

## 解决方案

1. ```
   将会话中的 CSRF 令牌存储为每个会话的随机值。示例（Python Flask）：`session['csrf_token'] = secrets.token_hex(32)` 并在视图中进行比较。
   ```
2. ```
   使用框架内置的 CSRF 保护，例如 Django 的 `{% csrf_token %}` 或 Spring Security 的 `CsrfTokenRepository` 配合 `HttpSessionCsrfTokenRepository`。
   ```
3. ```
   实现双重提交 Cookie：生成随机令牌，将其设置为 Cookie，并包含在隐藏的表单字段中；在服务器上验证两者是否匹配。
   ```

## 无效尝试

- **** — Using a static CSRF token for all users doesn't fix the issue; it makes the token easily guessable. (80% 失败率)
- **** — Only checking the token's presence, not its value, leaves the application vulnerable to token fixation. (70% 失败率)
- **** — Regenerating the token on every request without storing it in the session causes validation failures. (60% 失败率)
