做网站公司宣传语,城乡建设部官网,山西建设工程备案网站,永久免费的财务软件Spring Boot 结合 CORS 解决前端跨域问题
1. 背景
在前后端分离的项目中#xff0c;前端#xff08;例如 http://localhost:3000#xff09;调用后端接口#xff08;例如 http://localhost:8080#xff09;时#xff0c;浏览器会因为 同源策略 限制而阻止请求#xff0c…Spring Boot 结合 CORS 解决前端跨域问题
1. 背景
在前后端分离的项目中前端例如 http://localhost:3000调用后端接口例如 http://localhost:8080时浏览器会因为 同源策略 限制而阻止请求这就是所谓的 跨域问题。
同源策略要求
协议Protocol域名Domain端口Port
三者必须完全一致否则就会触发跨域。
跨域在前端调试、微服务接口调用、第三方 API 请求等场景中非常常见。为了让浏览器允许跨域访问需要配置 CORS跨域资源共享Cross-Origin Resource Sharing。2. 什么是 CORS
CORS 是 W3C 定义的一种跨域访问标准允许服务器在响应中添加特定的 HTTP 头让浏览器判断是否允许跨域请求。核心是以下响应头响应头作用Access-Control-Allow-Origin允许访问的源可以是具体域名或 *Access-Control-Allow-Methods允许的 HTTP 方法GET, POST, PUT, DELETE 等Access-Control-Allow-Headers允许的自定义请求头Access-Control-Allow-Credentials是否允许携带 CookieAccess-Control-Max-Age预检请求缓存时间秒
3. Spring Boot 中解决跨域的常用方法
3.1 方法一在 Controller 上使用 CrossOrigin
Spring Boot 提供了 CrossOrigin 注解可以快速在类或方法级别开启 CORS。
import org.springframework.web.bind.annotation.*;RestController
RequestMapping(/api/user)
CrossOrigin(origins http://localhost:3000) // 允许的前端地址
public class UserController {GetMapping(/{id})public String getUser(PathVariable Long id) {return 用户ID: id;}
}特点
适合局部跨域控制。不影响其他接口。缺点是需要在每个 Controller 手动加注解管理不便。3.2 方法二全局 CORS 配置推荐
如果你的接口都需要跨域访问可以通过 WebMvcConfigurer 全局配置。
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;Configuration
public class GlobalCorsConfig implements WebMvcConfigurer {Overridepublic void addCorsMappings(CorsRegistry registry) {registry.addMapping(/**) // 允许跨域的接口路径.allowedOriginPatterns(*) // 允许跨域的源Spring Boot 2.4 推荐用 allowedOriginPatterns.allowedMethods(GET, POST, PUT, DELETE, OPTIONS) // 允许的 HTTP 方法.allowedHeaders(*) // 允许的请求头.allowCredentials(true) // 是否允许携带 Cookie.maxAge(3600); // 预检请求缓存时间}
}特点
一次配置所有接口生效。方便统一管理。生产环境建议改成精确匹配允许的域名而不是 *。3.3 方法三使用 Filter 配置 CORS
通过自定义 CorsFilter 处理跨域请求可以在 Spring Boot 启动时加载。
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;Configuration
public class CorsFilterConfig {Beanpublic CorsFilter corsFilter() {CorsConfiguration config new CorsConfiguration();config.addAllowedOriginPattern(*);config.setAllowCredentials(true);config.addAllowedMethod(*);config.addAllowedHeader(*);config.setMaxAge(3600L);UrlBasedCorsConfigurationSource source new UrlBasedCorsConfigurationSource();source.registerCorsConfiguration(/**, config);return new CorsFilter(source);}
}特点
适用于需要跨越 Spring MVC、Spring Security 等多个层的情况。能解决某些全局配置不生效的问题。4. 配合 Spring Security 的特殊处理
如果项目使用了 Spring Security默认会拦截 OPTIONS 预检请求导致 CORS 配置不生效。这时需要额外在 Security 配置中开放 OPTIONS 请求。
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.SecurityFilterChain;Configuration
public class SecurityConfig {Beanpublic SecurityFilterChain filterChain(HttpSecurity http) throws Exception {http.cors().and().csrf().disable(); // 启用 CORS 禁用 CSRFhttp.authorizeHttpRequests().anyRequest().permitAll();return http.build();}
}关键点
http.cors() 会读取 WebMvcConfigurer 或 CorsFilter 中的配置。关闭 CSRF 主要是为了方便调试跨域生产环境需根据业务需求启用。5. 常见问题排查
前端依旧报跨域
确认是浏览器报的 CORS 错误而不是接口 404/500。确认后端响应中包含 Access-Control-Allow-Origin。
Cookie 不生效
后端 allowCredentials(true)。前端请求设置 fetch 或 Axios 的 withCredentials: true。注意当 allowCredentials(true) 时Access-Control-Allow-Origin 不能为 *。
Spring Security 版本冲突
Spring Boot 3.x 下要用 SecurityFilterChain 而不是 WebSecurityConfigurerAdapter已废弃。6. 总结
局部跨域 → CrossOrigin全局跨域推荐 → WebMvcConfigurer复杂场景如结合 Spring Security → CorsFilter SecurityConfig生产环境建议精确配置 allowedOrigins避免安全隐患。✅ 最佳实践推荐
Configuration
public class GlobalCorsConfig implements WebMvcConfigurer {Overridepublic void addCorsMappings(CorsRegistry registry) {registry.addMapping(/**).allowedOrigins(https://yourdomain.com) // 精确指定.allowedMethods(GET, POST, PUT, DELETE).allowedHeaders(*).allowCredentials(true).maxAge(3600);}
}配合
Configuration
public class SecurityConfig {Beanpublic SecurityFilterChain filterChain(HttpSecurity http) throws Exception {http.cors().and().csrf().disable();return http.build();}
}这样前端就可以愉快地调用后端接口而不会再被 CORS 卡住了。7.本质
CORS 在 Spring Boot 里的本质其实并不是靠普通的 拦截器HandlerInterceptor 去做的而是由 底层的 CORS 处理机制 在 Servlet Filter 层完成的。7.1. 核心机制
在 Spring WebSpring MVC里CORS 处理是通过 CorsProcessor 在请求进入 Controller 之前拦截并根据配置动态添加 CORS 响应头。
整个流程分两种情况
预检请求OPTIONS
浏览器先发一个 OPTIONS 请求询问服务器是否允许该跨域。Spring 的 CORS 处理器判断后直接返回带有 Access-Control-Allow-* 的响应并终止后续调用不进入 Controller。
实际请求GET、POST…
在进入 Controller 前CORS 处理器检查请求来源和方法是否合法如果允许就在响应头里加上 CORS 相关字段。7.2. Spring Boot 的执行链
当你用
CrossOriginWebMvcConfigurer#addCorsMappings()或 CorsFilter
配置 CORS 后Spring Boot 会
注册一个 CorsFilter 或 HandlerMappingIntrospector 内部的 CORS 拦截逻辑。请求进入 Servlet 容器后先走 Filter 链Spring CORS 逻辑会最先判断跨域。如果是 OPTIONS 预检且允许跨域直接返回响应不再走后续 Controller。如果是实际请求进入 Controller 处理业务逻辑但响应会自动加上 CORS 头。7.3. 为什么不用普通拦截器
普通的 HandlerInterceptor 只能拦截已经匹配到 Handler 的请求但 CORS 预检请求往往不需要进入业务 Controller。CORS 要尽早处理最好在 Filter 层拦截这样性能更好、逻辑更统一。Spring MVC 的 CORS 是在 DispatcherServlet 处理请求前就能处理的而拦截器是在 HandlerAdapter 调用前才运行。✅ 总结一句话
Spring Boot 的 CORS 本质是通过 Servlet Filter 层的 CorsFilter Spring MVC 的 CorsProcessor 在请求到达 Controller 前处理的而不是靠普通的业务拦截器实现的。