1774597379
This commit is contained in:
@@ -0,0 +1,53 @@
|
||||
`x-csrf-token` 是 Spring Security CSRF 防护机制 的一部分,用于防止跨站请求伪造(CSRF)攻击。
|
||||
|
||||
后端接口需要通过请求头接收前端携带的 CSRF token,以验证请求的合法性。
|
||||
|
||||
其中 IBSCsrfTokenRepository 管理 CSRF token,是一个 `UUID.randomUUID().toString()` 随机字符串
|
||||
|
||||
登录成功后,SecurityConfig.writeLoginSuccessResult()(SecurityConfig.java:482)会将 token 存入 session:request.getSession().setAttribute(IBSCsrfTokenRepository.class.getName() + ".CSRF_TOKEN", token)
|
||||
|
||||
同时通过 /admin/getCurrentUser 接口返回给前端:userVO.setCsrfToken(csrfToken.getToken())
|
||||
|
||||
```
|
||||
前端获取 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");
|
||||
|
||||
```
|
||||
|
||||
```
|
||||
在 SecurityConfig.csrf() 配置中(SecurityConfig.java:211-218),以下路径不进行 CSRF 校验:
|
||||
|
||||
// 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)));//不塞在cookie中
|
||||
```
|
||||
|
||||
如果请求路径在 ignorePathes 列表中(如 /v1/**, /api/**, /action, /actionpm 等),loadToken 返回硬编码的 "1111111111",此时:
|
||||
|
||||
请求带 X-CSRF-TOKEN: 1111111111 → 可以通过
|
||||
|
||||
请求带 X-CSRF-TOKEN: 任意UUID → 失败
|
||||
Reference in New Issue
Block a user