Files
notes/work/移动杭研/业务梳理/x-csrf-token.md
T
Docker7530 d17550351d 1774673562
2026-03-28 12:52:49 +08:00

42 lines
2.2 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
`x-csrf-token` 是 Spring Security CSRF 防护机制 的一部分,用于防止跨站请求伪造(CSRF)攻击。后端接口需要通过请求头接收前端携带的 CSRF token,以验证请求的合法性。
其中 IBSCsrfTokenRepository 管理 CSRF token,本质是一个 `UUID.randomUUID().toString()` 随机字符串。
登录成功后,`SecurityConfig.writeLoginSuccessResult()SecurityConfig.java:482` 会将 token 存入 session。
前端获取 Token,前端有两套机制,取决于环境:
```
生产环境(cdn-web 模板):页面通过 Thymeleaf 模板将 token 渲染到 HTML meta 标签中
<meta name="_csrf" th:content="${_csrf.token}">
<meta name="_csrf_header" th:content="${_csrf.headerName}">
前端通过 getCsrfHeaderFromMeta() 读取这两个 meta 标签,动态设置请求头。
非生产环境(IBS-web):通过调用 /admin/getCurrentUser 接口获取 token 并缓存在 window.XTOKEN 中。
```
后端 Filter 链验证 Token RequestReplaceFilter
```
response.setHeader("Access-Control-Allow-Headers", "content-type,x-requested-with,Authorization, x-request-with,x-ui-request,lang,x-csrf-token,csrf-token");
```
```
// CSRF
String[] ignorePathes = {"/v1/**", "/v2/**", "/v1.0/**", "/analyzer/**", "/puppet/**", "/api/**",
"/sso/**", "/ssoapi/**", "/dss/prohibit/**", "/dss/v1/log/subscribe/callback", "/portal/**",
"/param/config/**", "/bboss/**", "/sync/BBOSS/**", "/download/exportFile", "/action", "/actionpm",
"/action/cms", "/action/cdn/statistics", "/action/enterprise/domains","/action/enterprise/productId/domains",
"/action/js", "/content/delivery/**", "/information/**","/testAction","/api/v2/**",
"/home/page/help/Doc/**", "/home/page/security/**", "/query/cmcc/party/**", "/query/enterprise/domain/info", "/v2.0/log/template/**"};
http.csrf().ignoringAntMatchers(ignorePathes)
.csrfTokenRepository(new IBSCsrfTokenRepository(Arrays.asList(ignorePathes)));
```
如果请求路径在 ignorePathes 列表中(如 /v1/, /api/, /action, /actionpm 等),loadToken 返回硬编码的 "1111111111",此时:
请求带 X-CSRF-TOKEN: 1111111111 → 可以通过
请求带 X-CSRF-TOKEN: 任意UUID → 失败