Spring Boot 跨域配置类
CorsConfig.java
下面是一个完整的跨域配置类,适用于 Spring Boot 应用程序,可以去除CorsFilter以及添加CORS过滤器在Spring Security过滤器链前:
package com.cxy.cbms.config;
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;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class CorsConfig implements WebMvcConfigurer {
/**
* 全局跨域配置
* 使用 WebMvcConfigurer 的方式配置跨域
*/
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**") // 所有接口
.allowedOriginPatterns("*") // 允许所有来源
.allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS") // 允许的方法
.allowedHeaders("*") // 允许所有请求头
.allowCredentials(true) // 允许发送cookie
.maxAge(3600L); // 预检请求的有效期,单位为秒
}
/**
* 基于过滤器的跨域配置
* 这种方式适用于Spring Security环境
*/
@Bean
public CorsFilter corsFilter() {
CorsConfiguration config = new CorsConfiguration();
// 允许所有来源
config.addAllowedOriginPattern("*");
// 允许发送Cookie
config.setAllowCredentials(true);
// 允许所有头
config.addAllowedHeader("*");
// 允许所有方法
config.addAllowedMethod("*");
// 预检请求的有效期,单位为秒
config.setMaxAge(3600L);
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
// 对所有接口应用这些CORS配置
source.registerCorsConfiguration("/**", config);
return new CorsFilter(source);
}
}
Spring Security 集成说明
如果你使用了 Spring Security,还需要在安全配置中启用 CORS:
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Autowired
private CorsFilter corsFilter;
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
// 添加CORS支持
.cors()
.and()
// 其他安全配置
.csrf().disable()
.authorizeHttpRequests()
// ...其他配置
;
// 添加CORS过滤器在Spring Security过滤器链的最前面
http.addFilterBefore(corsFilter, ChannelProcessingFilter.class);
return http.build();
}
}
注意事项
-
生产环境安全性:在实际部署中,应该限制允许的来源而不是使用通配符
*
// 例如: config.addAllowedOrigin("https://your-trusted-domain.com"); config.addAllowedOrigin("https://another-trusted-domain.com");
-
更精细的控制:可以为不同的API路径配置不同的CORS策略
registry.addMapping("/api/public/**").allowedOrigins("*"); registry.addMapping("/api/admin/**").allowedOrigins("https://admin.your-domain.com");
-
暴露额外的响应头:如果需要客户端访问自定义响应头
config.addExposedHeader("Authorization"); config.addExposedHeader("X-Custom-Header");
这个配置类提供了两种配置跨域的方式,你可以根据你的项目需求选择使用其中一种或同时使用两种。通常在有 Spring Security 的情况下,建议使用基于过滤器的方式。