解决跨域访问问题
CI/CD Deploy (Admin) / 构建后端镜像并部署 (push) Successful in 1m39s

This commit is contained in:
张家训
2026-09-03 17:47:45 +08:00
parent 9f5e6920ac
commit d20fa6ab00
2 changed files with 50 additions and 21 deletions
@@ -15,6 +15,8 @@ import org.springframework.security.web.authentication.UsernamePasswordAuthentic
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import java.util.Collections;
/**
* @author zhangjiaxun
* @date 2021/1/5 17:40
@@ -100,23 +102,41 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
}
/**
* 跨越配置
* 跨域配置
*
* 生产环境页面与后端同源(web 容器 nginx 将 /api/* 反代到 backend),但浏览器对
* 同源 POST 请求同样会携带 Origin 头,而 Spring 5.x 的 CORS 过滤器只要检测到
* Origin 头即按跨域请求处理,来源不在白名单内会直接返回 403。
* 这里动态放行:
* - 同源请求(Origin 的 host 与请求 Host 一致):回显该 Origin;
* - 跨域请求:仅放行本地开发来源 http://localhost:8080(npm run dev);
* - 无 Origin 的非浏览器请求:不做 CORS 限制。
*/
@Bean
public CorsConfigurationSource corsConfigurationSource() {
return httpServletRequest -> {
return request -> {
String origin = request.getHeader("Origin");
if (origin == null) {
return null; // 非浏览器请求,不应用 CORS 处理
}
CorsConfiguration cfg = new CorsConfiguration();
String reqHost = request.getHeader("Host");
String originHost = origin.replaceFirst("^https?://", "").split("[:/]")[0];
boolean sameOrigin = originHost != null && originHost.equalsIgnoreCase(
reqHost == null ? "" : reqHost.split(":")[0]);
cfg.setAllowCredentials(true);
if (sameOrigin) {
// 同源回显,确保经任意入口(如 8880 反代)访问都放行
cfg.setAllowedOriginPatterns(Collections.singletonList(origin));
} else if ("localhost".equalsIgnoreCase(originHost) || "127.0.0.1".equals(originHost)) {
cfg.setAllowedOriginPatterns(Collections.singletonList("http://localhost:8080"));
} else {
cfg.setAllowedOriginPatterns(Collections.emptyList());
}
// 允许任何请求头/方法
cfg.addAllowedHeader("*");
cfg.addAllowedMethod("*");
// 设置允许跨域请求的域名
cfg.addAllowedOrigin("http://localhost:8080");
// 允许任何请求
cfg.addAllowedHeader("*");
cfg.addExposedHeader("token");
// 是否允许证书
cfg.setAllowCredentials(true);
//
cfg.checkOrigin("http://localhost:8080");
return cfg;
};
}