升级SecurityFilterChain后Spring Boot CORS配置失效问题求助
问题原因
你在新代码里错误禁用了Spring Security的CORS支持:http.cors((cors)->cors.disable()),但原代码中的http.cors().and().csrf().disable()是启用Spring Security的CORS过滤器,再禁用CSRF。
对于受保护的接口,浏览器会先发送OPTIONS预检请求,这个请求不会进入控制器的@CrossOrigin逻辑,而是被Spring Security拦截。当你禁用Security的CORS支持后,预检请求无法通过,就会触发CORS错误;而/public/**因为被设置为permitAll(),预检请求直接被允许,所以可以正常访问。
解决方案
修改SecurityFilterChain中的CORS配置,启用Spring Security的CORS支持,而非禁用:
@Bean SecurityFilterChain filterChain(HttpSecurity http) throws Exception { // 启用Spring Security的CORS支持(使用默认配置) http.cors(Customizer.withDefaults()); http.csrf((csrf) -> csrf.disable()); http.sessionManagement((sessionManagement) -> sessionManagement.sessionCreationPolicy(SessionCreationPolicy.STATELESS)); http.addFilterBefore(new AuthorizationFilter(authenticationManager(http.getSharedObject(AuthenticationConfiguration.class)), this.userRepository), UsernamePasswordAuthenticationFilter.class); http.authorizeHttpRequests((request) -> request .requestMatchers(HttpMethod.OPTIONS, "/**").permitAll() // 允许所有OPTIONS预检请求 .requestMatchers("/public/**").permitAll() .anyRequest().authenticated()); return http.build(); }
如果需要自定义CORS规则(比如指定允许的源、请求方法等),可以额外配置一个CorsConfigurationSource Bean来替代默认配置:
@Bean CorsConfigurationSource corsConfigurationSource() { CorsConfiguration configuration = new CorsConfiguration(); // 指定允许的前端源 configuration.setAllowedOrigins(Collections.singletonList("http://localhost:4200")); // 允许的请求方法 configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS")); // 允许的请求头 configuration.setAllowedHeaders(Arrays.asList("Authorization", "Content-Type")); // 允许携带凭证 configuration.setAllowCredentials(true); UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); // 对所有路径应用该CORS规则 source.registerCorsConfiguration("/**", configuration); return source; }
配置完成后,Spring Security会处理所有请求的CORS逻辑(包括预检请求),配合控制器的@CrossOrigin(或直接依赖全局配置)就能解决受保护接口的CORS问题。
内容的提问来源于stack exchange,提问作者steeve
相关产品推荐
相关产品推荐

