【SpringBoot】WebConfig 跨域配置详细说明
功能概述
WebConfig
是一个 Spring Boot 配置类,主要用于配置跨域资源共享 (CORS) 策略,解决前端应用访问后端 API 时的跨域问题。
package com.example.springboot.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;/*** Web配置类* 用于配置跨域资源共享(CORS)等Web相关设置*/
@Configuration
public class WebConfig {/*** 配置跨域资源共享* 允许前端应用访问后端API* * @return CorsFilter*/@Beanpublic CorsFilter corsFilter() {CorsConfiguration config = new CorsConfiguration(); // 允许所有域名进行跨域调用config.addAllowedOriginPattern("*"); // 允许跨越发送cookieconfig.setAllowCredentials(true); // 放行全部原始头信息config.addAllowedHeader("*"); // 允许所有请求方法跨域调用config.addAllowedMethod("*");UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();source.registerCorsConfiguration("/**", config);return new CorsFilter(source);}
}
配置详情
跨域配置 (CORS)
通过 corsFilter()
方法配置了一个全局的 CORS 过滤器:
-
允许的源:
config.addAllowedOriginPattern("*")
: 允许所有域名进行跨域访问- 注意:在生产环境中,建议替换为具体的前端域名而非通配符,以增强安全性
-
凭证支持:
config.setAllowCredentials(true)
: 允许跨域请求携带认证信息(如 cookies)
-
请求头设置:
config.addAllowedHeader("*")
: 允许所有请求头信息
-
HTTP 方法:
config.addAllowedMethod("*")
: 允许所有 HTTP 方法(GET, POST, PUT, DELETE 等)
-
路径匹配:
source.registerCorsConfiguration("/**", config)
: 对所有路径应用此 CORS 配置
使用建议
-
生产环境调整:
- 建议将
addAllowedOriginPattern("*")
替换为具体的前端域名,例如:config.addAllowedOriginPattern("https://yourdomain.com"); config.addAllowedOriginPattern("https://yourotherdomain.com");
- 建议将
-
安全性考虑:
- 如果不需要凭证,应将
setAllowCredentials(false)
以提高安全性 - 可以根据实际需求限制允许的 HTTP 方法和请求头
- 如果不需要凭证,应将
-
测试环境:
- 当前配置非常适合开发和测试环境
- 允许所有来源、方法和头部的配置便于前端开发调试
集成方式
该配置类会自动被 Spring Boot 加载,无需额外配置。只需确保该类位于主应用类所在的包或其子包中。
版本兼容性
- 适用于 Spring Boot 2.4.x 及以上版本
addAllowedOriginPattern
方法在 Spring Boot 2.4.0 引入,替代了之前版本的addAllowedOrigin
转载吱一声~