Spring Security CSRF防护与CORS配置实战指南

发布时间:2026/7/21 5:58:18
Spring Security CSRF防护与CORS配置实战指南 1. Spring Security中的CSRF防护机制解析CSRFCross-Site Request Forgery跨站请求伪造是Web应用中常见的安全威胁。Spring Security默认会对所有非安全HTTP方法如POST、PUT等启用CSRF防护。其核心原理是通过同步器令牌模式服务端生成唯一令牌CsrfToken令牌存储在会话或Cookie中客户端需在后续请求中携带该令牌服务端验证令牌有效性1.1 默认配置与工作原理Spring Security 6.x的默认CSRF配置包含以下关键组件Configuration EnableWebSecurity public class SecurityConfig { Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http .csrf(Customizer.withDefaults()); // 启用默认CSRF防护 return http.build(); } }默认实现包含三个核心部分HttpSessionCsrfTokenRepository- 将令牌存储在HttpSession中XorCsrfTokenRequestAttributeHandler- 提供BREACH攻击防护CsrfFilter- 处理实际的令牌验证逻辑关键点从Spring Security 6开始CSRF令牌加载改为延迟模式只有需要验证的请求才会加载会话这显著提升了性能。1.2 令牌存储策略对比Spring Security提供两种主要的令牌存储方式存储方式实现类适用场景优点缺点Session存储HttpSessionCsrfTokenRepository传统Web应用安全性高需要会话支持Cookie存储CookieCsrfTokenRepositorySPA/前后端分离无状态需防范XSSCookie存储的典型配置http.csrf(csrf - csrf .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()) );1.3 禁用CSRF防护的场景在某些API-only的应用中可能需要禁用CSRFhttp.csrf(csrf - csrf.disable());更精细的控制方式是指定忽略路径http.csrf(csrf - csrf .ignoringRequestMatchers(/api/public/**) );2. CORS跨域配置实战2.1 CORS与CSRF的关系虽然都涉及跨域安全但CORS和CSRF解决的是不同层面的问题CORS控制哪些外部域可以访问资源CSRF防止未授权的命令执行2.2 Spring Security中的CORS配置全局CORS配置示例Bean public CorsConfigurationSource corsConfigurationSource() { CorsConfiguration config new CorsConfiguration(); config.setAllowedOrigins(List.of(https://trusted.com)); config.setAllowedMethods(List.of(GET,POST)); config.setAllowCredentials(true); UrlBasedCorsConfigurationSource source new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration(/**, config); return source; }与Spring Security集成http.cors(cors - cors .configurationSource(corsConfigurationSource()) );2.3 常见CORS错误处理遇到has been blocked by CORS policy错误时检查预检请求(OPTIONS)是否通过响应头是否包含Access-Control-Allow-Origin带凭证请求时是否设置allowCredentialstrue复杂请求是否声明了Access-Control-Allow-Methods3. Session管理高级配置3.1 会话固定保护Spring Security默认启用会话固定保护http.sessionManagement(session - session .sessionFixation().migrateSession() );可选策略changeSessionId仅更改IDServlet 3.1migrateSession创建新会话并复制属性默认newSession创建全新会话none禁用保护3.2 并发会话控制限制单个用户的会话数量http.sessionManagement(session - session .maximumSessions(1) .maxSessionsPreventsLogin(true) );3.3 会话超时处理结合CSRF时需特别注意Bean public HttpSessionEventPublisher httpSessionEventPublisher() { return new HttpSessionEventPublisher(); }配置会话失效URLhttp.sessionManagement(session - session .invalidSessionUrl(/session-expired) );4. 综合配置示例4.1 安全配置模板Configuration EnableWebSecurity public class SecurityConfig { Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http .cors(cors - cors .configurationSource(corsConfigurationSource()) ) .csrf(csrf - csrf .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()) .ignoringRequestMatchers(/api/public/**) ) .sessionManagement(session - session .sessionFixation().migrateSession() .maximumSessions(1) .expiredUrl(/session-expired) ); return http.build(); } Bean public CorsConfigurationSource corsConfigurationSource() { // 同上文CORS配置 } }4.2 测试配置要点测试CSRF防护的MockMvc示例Autowired private WebApplicationContext context; private MockMvc mockMvc; BeforeEach void setup() { mockMvc MockMvcBuilders .webAppContextSetup(context) .apply(springSecurity()) .build(); } Test void postWithValidCsrf() throws Exception { mockMvc.perform(post(/submit) .with(csrf())) // 自动添加有效CSRF令牌 .andExpect(status().isOk()); }5. 疑难问题排查指南5.1 CSRF相关错误问题1InvalidCsrfTokenException可能原因表单缺少_csrf参数AJAX请求未携带X-CSRF-TOKEN头会话超时导致令牌失效解决方案检查表单是否包含input typehidden name_csrf th:value${_csrf.token}/对于AJAX请求添加headers: {X-CSRF-TOKEN: token}问题2CookieCsrfTokenRepository不工作检查点是否设置了withHttpOnlyFalse()前端是否正确读取XSRF-TOKEN cookie是否在请求头中携带X-XSRF-TOKEN5.2 CORS相关错误问题预检请求失败典型表现Response to preflight request doesnt pass access control check解决方案确保OPTIONS请求不被拦截.requestMatchers(HttpMethod.OPTIONS).permitAll()检查CORS配置是否包含所需方法config.setAllowedMethods(List.of(GET,POST,PUT,DELETE,OPTIONS));5.3 Session相关错误问题session persistence异常现象重启后会话丢失集群环境下会话不同步解决方案配置持久化Session存储spring.session.store-typeredis添加依赖dependency groupIdorg.springframework.session/groupId artifactIdspring-session-data-redis/artifactId /dependency6. 性能优化建议CSRF令牌延迟加载Spring Security 6默认// 无需特别配置默认已启用会话优化减少会话中存储的数据量考虑使用session.statelesstrue的无状态架构CORS缓存config.setMaxAge(3600L); // 预检结果缓存1小时异步处理http.sessionManagement(session - session .sessionCreationPolicy(SessionCreationPolicy.ALWAYS) );实际项目中我曾遇到一个SPA应用因频繁预检请求导致性能下降的情况。通过调整CORS缓存时间和精简允许的方法列表最终将API响应时间降低了40%。关键配置如下config.setAllowedMethods(List.of(GET,POST)); // 仅允许必要方法 config.setMaxAge(7200L); // 预检缓存2小时