什么是 CORS(跨域资源共享)?
CORS(Cross-Origin Resource Sharing) 是浏览器的一种安全机制,用来防止网站之间恶意请求用户的敏感数据。
举个例子:
你的后端地址是:
http://localhost:8080
你的前端 Vue/React 项目运行在:
http://localhost:5173
这两个端口不同,属于不同源。当你从前端发起 AJAX 请求访问后端 API,就触发了“跨域”。
除此以外,http://localhost:8080和https://localhost:8080这种协议不同也属于跨域,域名不同也跨域。
默认情况:浏览器会阻止这种跨域请求
也就是说请求根本没到后端就被浏览器拦截了,可能会发生错误例如:
Access to fetch at 'http://localhost:8080/api/user' from origin 'http://localhost:5173' has been blocked by CORS policy:
No 'Access-Control-Allow-Origin' header is present on the requested resource.
所以你必须在后端开启 CORS 跨域支持,告诉浏览器:
“我信任这个前端域名,它是可以访问我的!”
Spring Security 中开启跨域的标准方式是配置一个 CorsConfigurationSource Bean
@Bean
public CorsConfigurationSource configurationSource() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowedOrigins(Arrays.asList("*")); // ✅ 允许所有来源访问(调试用)
config.setAllowedMethods(Arrays.asList("*")); // ✅ 允许所有请求方法:GET POST PUT DELETE 等
config.setAllowedHeaders(Arrays.asList("*")); // ✅ 允许所有请求头(包括 Authorization 等)
source.registerCorsConfiguration("/**", config); // ✅ 应用于所有路径
return source;
}
| 配置项 | 含义 | 示例值 | 建议 |
|---|---|---|---|
setAllowedOrigins() | 允许哪些前端域名访问 | *(所有域名) | 开发可用,生产应写死为 http://your-frontend.com |
setAllowedMethods() | 允许哪些 HTTP 方法 | GET, POST, PUT, DELETE | 建议只配置用到的请求方法 |
setAllowedHeaders() | 允许哪些请求头 | 常见:Authorization, Content-Type | * 可行但不推荐用于生产 |
registerCorsConfiguration("/**", config) | 应用于所有 API 路径 | /api/** | /** 表示全局跨域配置 |
我们来稍微说一下最后一个registerCors Configuration,“/api/**”表示只允许跨域访问 /api 开头的接口,“/user/**”这种就不能跨域访问
如何启用这个配置?
Spring Security 中,你需要在SecurityFilterChain里的 HttpSecurity 中加入:
.cors(cors -> cors.configurationSource(configurationSource()))
这句话告诉 Spring Security:
使用你自定义的 CorsConfigurationSource Bean 来处理所有跨域请求。

5510

被折叠的 条评论
为什么被折叠?



