| | |
| | | import java.util.List; |
| | | |
| | | /** |
| | | * 跨域配置:只允许配置中列出的来源访问接口。 |
| | | * 前后端分离本地开发默认放行 8080;前端经 dev-server 代理或与后端同源部署时均不需要额外放行。 |
| | | * 跨域配置:只允许配置中列出的来源(支持 * 通配)访问接口。 |
| | | * 浏览器发起 POST/PUT/DELETE 时会带 Origin 头(GET 不带),因此用局域网 IP 打开页面时, |
| | | * 若该来源不在放行列表内会被 CorsFilter 判为非法并返回 403,表现为登录时提示“网络错误”。 |
| | | * 默认放行本机与内网网段的任意端口(本地开发、局域网访问、IP 方式访问 8090 同源部署都覆盖)。 |
| | | * 注意:不开启 allowCredentials(接口用 Bearer 令牌鉴权,不依赖 Cookie),避免任意站点携带凭证调用。 |
| | | */ |
| | | @Configuration |
| | | public class CorsConfig { |
| | | |
| | | @Value("${app.cors.allowed-origins:http://localhost:8080,http://127.0.0.1:8080}") |
| | | @Value("${app.cors.allowed-origins:http://localhost:*,http://127.0.0.1:*,http://192.168.*:*,http://10.*:*,http://172.*:*}") |
| | | private String allowedOrigins; |
| | | |
| | | private List<String> originList() { |
| | |
| | | @Bean |
| | | public CorsConfigurationSource corsConfigurationSource() { |
| | | CorsConfiguration config = new CorsConfiguration(); |
| | | config.setAllowedOrigins(originList()); |
| | | config.setAllowedOriginPatterns(originList()); |
| | | config.setAllowedHeaders(Arrays.asList("Authorization", "Content-Type", "Accept", "X-Requested-With")); |
| | | config.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS")); |
| | | config.setAllowCredentials(false); |
| | |
| | | public CorsFilter corsFilter() { |
| | | return new CorsFilter(corsConfigurationSource()); |
| | | } |
| | | } |
| | | } |