SpringMvc跨域配置方法详解
在 Spring MVC 中,通过 CorsRegistry.addMapping()
返回的 CorsRegistration
对象提供了以下方法用于配置跨域属性(基于 Spring Framework 5.x/6.x):
核心配置方法:
-
allowedOrigins(String... origins)
- 设置允许的源(协议+域名+端口)
- 示例:
.allowedOrigins("https://example.com", "http://localhost:8080")
- 特殊值:
"*"
允许所有源(与allowCredentials(true)
互斥)
-
allowedOriginPatterns(String... patterns)
(Spring 5.3+)- 使用通配符模式匹配源(更灵活)
- 示例:
.allowedOriginPatterns("https://*.example.com", "http://localhost:*")
-
allowedMethods(String... methods)
- 设置允许的 HTTP 方法(GET/POST 等)
- 示例:
.allowedMethods("GET", "POST", "PUT")
- 特殊值:
"*"
允许所有方法
-
allowedHeaders(String... headers)
- 设置允许的请求头
- 示例:
.allowedHeaders("Authorization", "Content-Type")
- 特殊值:
"*"
允许所有头(实际请求头需显式列出)
-
exposedHeaders(String... headers)
- 设置浏览器可访问的响应头
- 示例:
.exposedHeaders("X-Custom-Header", "Content-Disposition")
-
allowCredentials(Boolean allowCredentials)
- 是否允许发送 Cookie/HTTP 认证
- 示例:
.allowCredentials(true)
- 重要:设为
true
时,allowedOrigins/originPatterns
不能为"*"
-
maxAge(Long maxAge)
- 设置预检请求(OPTIONS)的缓存时间(秒)
- 示例:
.maxAge(1800)
(缓存 30 分钟)
完整配置示例:
@Override
public void addCorsMappings(CorsRegistry registry) {registry.addMapping("/api/**").allowedOriginPatterns("https://*.example.com", "http://localhost:*").allowedMethods("GET", "POST", "PUT", "DELETE").allowedHeaders("Authorization", "Content-Type", "X-Requested-With").exposedHeaders("X-Custom-Header", "Content-Length").allowCredentials(true).maxAge(3600); // 1小时缓存
}
关键注意事项:
-
addMapping
路径匹配:registry.addMapping("/**")
:匹配所有路径registry.addMapping("/api/**")
:匹配/api
开头的路径
-
优先级规则:
- 更具体的路径映射优先级高于通配符路径
- 示例:
/api/users/**
的配置会覆盖/api/**
的配置
-
allowedHeaders("*")
的限制:- 实际允许的头不包括
"*"
,需显式列出所有头(如Authorization
等) - 安全建议:避免使用
"*"
,明确指定所需头
- 实际允许的头不包括
-
allowCredentials(true)
的安全约束:- 必须与具体的
allowedOrigins/originPatterns
配合使用 - 禁止与
allowedOrigins("*")
组合(浏览器会阻止)
- 必须与具体的
提示:Spring Boot 2.4+ 推荐使用
allowedOriginPatterns
替代allowedOrigins
,因其支持更灵活的域匹配模式。