# AJAX请求头中缺少CSRF令牌

- **ID:** `security/csrf-token-missing-in-ajax-request`
- **领域:** security
- **类别:** auth_error
- **错误码:** `403`
- **验证级别:** ai_generated
- **修复率:** 90%

## 根因

前端JavaScript代码未在AJAX请求的X-CSRF-Token头中包含CSRF令牌，导致服务端中间件以403状态拒绝请求。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| Django 4.2 | active | — | — |
| Spring Security 6.1 | active | — | — |
| Rails 7.0 | active | — | — |

## 解决方案

1. ```
   在前端，添加全局AJAX设置以包含CSRF令牌。对于jQuery：$.ajaxSetup({ headers: { 'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content') } })
   ```
2. ```
   确保包含CSRF令牌的meta标签在HTML模板中渲染，并且JavaScript代码可以访问它。
   ```
3. ```
   使用自动从cookie或meta标签添加CSRF头到所有请求的fetch包装器。
   ```

## 无效尝试

- **** — Disabling CSRF protection globally in the framework removes a critical security control, making the application vulnerable to CSRF attacks. (70% 失败率)
- **** — Only adding the token to form submissions but not to AJAX requests leaves the AJAX endpoints unprotected. (50% 失败率)
- **** — Placing the token in a query parameter instead of a header can leak it in server logs and browser history. (60% 失败率)
