Spring Boot 跨域过滤器配置详解
Spring Boot 跨域过滤器配置详解
public CorsFilter corsFilter() {
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
// 设置访问源地址
config.addAllowedOriginPattern("*");
// 设置访问源请求头
config.addAllowedHeader("*");
// 设置访问源请求方法
config.addAllowedMethod("*");
// 有效期 1800秒
config.setMaxAge(1800L);
// 添加映射路径,拦截一切请求
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", config);
// 返回新的CorsFilter
return new CorsFilter(source);
}
这段代码定义了一个 CorsFilter 过滤器,用于处理跨域访问请求。代码已经基本完整,但可根据具体业务需求进行调整。
可优化配置:
- 添加拦截路径: 可以根据实际业务需求,添加需要拦截的路径,例如:
source.registerCorsConfiguration("/api/**", config);
- 设置特定的请求头: 可以根据具体的业务需求,设置特定的请求头,例如:
config.addAllowedHeader("Authorization");
config.addAllowedHeader("Content-Type");
- 设置特定的请求方法: 可以根据具体的业务需求,设置特定的请求方法,例如:
config.addAllowedMethod("GET");
config.addAllowedMethod("POST");
- 设置特定的访问源地址: 可以根据实际业务需求,设置特定的访问源地址,例如:
config.addAllowedOrigin("http://example.com");
config.addAllowedOrigin("http://another-example.com");
- 设置有效期: 可以根据具体的业务需求,设置特定的有效期,例如:
config.setMaxAge(3600L); // 有效期 3600 秒
总结:
根据具体的业务需求,可以根据需要修改或添加一些配置,让代码更加完善和符合实际的业务需求。
原文地址: https://www.cveoy.top/t/topic/mQk5 著作权归作者所有。请勿转载和采集!