前后端分离情况下的跨域资源共享如何理解,Spring Security如何配置

什么是 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 来处理所有跨域请求。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值