Spring Security中自定义JWT过滤器的CORS问题解决方案咨询
解决自定义JWT过滤器返回错误时的CORS头缺失问题
问题根源在于你配置的WebMvcConfigurer的CORS规则是在Spring MVC的DispatcherServlet阶段生效的,而你的自定义JWT过滤器属于SecurityFilterChain,执行顺序早于DispatcherServlet。当过滤器直接返回400响应时,请求根本没走到MVC层,自然不会带上CORS头。
不需要手动在过滤器里设置响应头,用Spring Security自带的CORS配置即可解决,步骤如下:
1. 替换WebMvc的CORS配置为Spring Security的CORS配置
删除WebMvcConfigurer中的addCorsMappings方法,改为在SecurityFilterChain中配置CORS:
@Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http // 启用Security的CORS处理 .cors(cors -> cors.configurationSource(corsConfigurationSource())) // 添加你的自定义JWT过滤器(注意顺序,要放在UsernamePasswordAuthenticationFilter之前) .addFilterBefore(yourJwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class) // 其他Security配置(比如禁用csrf、配置授权规则等) .csrf(csrf -> csrf.disable()) .authorizeHttpRequests(auth -> auth .anyRequest().authenticated() ); return http.build(); } // 定义CORS配置源 @Bean public CorsConfigurationSource corsConfigurationSource() { CorsConfiguration corsConfig = new CorsConfiguration(); // 允许的源,和你之前WebMvc配置一致 corsConfig.setAllowedOrigins(List.of("http://localhost:3000")); // 允许的请求方法 corsConfig.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE")); // 允许的请求头 corsConfig.setAllowedHeaders(List.of("*")); // 如果前端需要携带凭证(如Cookie),可以开启下面这行 // corsConfig.setAllowCredentials(true); UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); // 对所有路径应用该CORS规则 source.registerCorsConfiguration("/**", corsConfig); return source; }
2. 原理说明
Spring Security会自动添加一个CorsFilter到过滤器链的最前端,所有请求(包括你的自定义过滤器直接返回的错误响应)都会先经过这个过滤器处理,自动为响应添加所需的CORS头。这样不管JWT验证是否通过,跨域请求都能正确获取到响应头,避免前端出现跨域错误。
内容的提问来源于stack exchange,提问作者Алексей
相关产品推荐
相关产品推荐

