代码
适用于SpringBoot3.x
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
/**
* 配置全局跨域
* SpringBoot自定义拦截器和跨域配置冲突
* 当有请求发送到后台时,先被自定义拦截器拦截,如果拦截器验证没有问题,才会开始执行跨域配置。
* 解决办法:
* 让跨域配置在自定义拦截器之前执行,由于 Filter 的执行顺序大于自定义拦截器,因此可以在 Filter 中实现跨域的配置
*/
@Configuration
public class GlobalCorsFilter {
private CorsConfiguration corsConfig() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedHeader("*");
corsConfiguration.addAllowedMethod("*");
corsConfiguration.addAllowedOriginPattern("*");
corsConfiguration.setMaxAge(3600L);
corsConfiguration.setAllowCredentials(true);
return corsConfiguration;
}
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", corsConfig());
return new CorsFilter(source);
}
}