Spring Boot基于PHPSESSID的自定义认证过滤器启用后CORS报错如何解决?
问题根因
出现CORS报错的核心原因是请求处理链路的优先级错位:
- Spring Security的全局过滤代理(
DelegatingFilterProxy)默认执行优先级为-100,比你单独配置的order=0的CORS过滤器优先级更高。也就是说,所有请求会先走完Spring Security的整条过滤链,才会轮到你配置的独立CORS过滤器。 - 你自定义的认证过滤器会优先在Security链里拦截请求:跨域场景下浏览器发送的
OPTIONS预检请求本身不会携带Cookie,根本通不过会话校验,被直接返回401。此时请求还没走到后面的CORS过滤器,响应里完全没有Access-Control-*系列的跨域允许头,浏览器自然判定为CORS错误。 - 原有CORS配置没有开启跨域凭证支持,就算顺序调整正确,携带Cookie的跨域请求依然会被浏览器拦截。
正确配置方式
1. 启用Spring Security内置的CORS集成
不要依赖独立的Servlet层CORS过滤器和Security链抢优先级,直接把CORS处理逻辑嵌入到Security过滤链的最前端,保证它比自定义认证过滤器先执行:
@Configuration @EnableWebSecurity(debug = true) public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http // 启用内置CORS支持,自动匹配后续定义的CorsConfigurationSource .cors() .and() // 自定义认证过滤器放到CORS逻辑之后执行 .addFilterBefore(new MainAppAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class) .csrf().disable() .authorizeRequests() // 明确放行所有跨域预检请求,避免被后续认证逻辑拦截 .antMatchers(CorsUtils::isPreFlightRequest).permitAll() .anyRequest().permitAll() .and().httpBasic(); } // 替换原来的独立FilterRegistrationBean,给Security提供专属CORS配置 @Bean public CorsConfigurationSource corsConfigurationSource() { CorsConfiguration config = new CorsConfiguration(); // 必须明确指定允许的源,开启凭证支持后不能用通配* config.setAllowedOrigins(Collections.singletonList("http://localhost")); config.setAllowedMethods(Collections.singletonList("*")); config.setAllowedHeaders(Collections.singletonList("*")); // 必须开启允许携带Cookie,否则跨域带PHPSESSID的请求会被拦截 config.setAllowCredentials(true); UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", config); return source; } }
2. 修复自定义认证过滤器的逻辑
原有的过滤器逻辑存在两个漏洞,需要调整:
- 直接放行所有
OPTIONS方法的预检请求,不做会话校验 - 不要在校验失败时直接短路返回错误,保证请求能正常走完后续过滤链,让CORS响应头能正常写入
public class MainAppAuthenticationFilter extends GenericFilterBean { @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpRequest = (HttpServletRequest) request; // 直接放行所有跨域预检请求,不做认证校验 if (HttpMethod.OPTIONS.matches(httpRequest.getMethod())) { chain.doFilter(request, response); return; } Cookie[] cookies = httpRequest.getCookies(); // 原有会话校验逻辑 User user = userIsValid(cookies); if (user != null) { Authentication authentication = new UsernamePasswordAuthenticationToken( user.getName(), null, AuthorityUtils.createAuthorityList(user.getRole()) ); SecurityContextHolder.getContext().setAuthentication(authentication); } // 无论校验结果如何,都继续走后续过滤链,不要直接sendError短路 chain.doFilter(request, response); } }
注意事项
- 开启
allowCredentials=true后,CORS配置里的允许源不能用*通配,必须明确写出所有可访问的前端域名,否则浏览器会直接拦截带Cookie的请求 - 如果需要对未通过校验的请求返回401响应,需要借助Spring Security的
AuthenticationEntryPoint配置统一处理,不要在自定义过滤器里直接短路,避免丢失已经写入的CORS响应头
内容的提问来源于stack exchange,提问作者s1n7ax
相关产品推荐
相关产品推荐

