You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JHipster配置Content-Security-Policy跨域请求问题排查

JHipster跨域CSP策略不生效问题排查

问题重现

两个JHipster Spring Boot应用,开发环境下应用A运行于localhost:8083,应用B运行于localhost:8080。应用A新增的API用Postman调用正常,但从应用B的Angular表单调用时出现CSP报错:

polyfills.1266a5de5d4c3910.js:1 Refused to connect to 'http://www.localhost:8083/MYURL' because it violates the following Content Security Policy directive: "default-src 'self'". Note that 'connect-src' was not explicitly set, so 'default-src' is used as a fallback.

修改应用A的SecurityConfiguration.java中的CSP配置为硬编码的default-src *; connect-src *后,报错依然存在。


排查步骤

1. 修正前端请求地址错误

报错中请求的地址是http://www.localhost:8083/MYURL,www.localhost是无效域名(localhost无需添加www前缀),先确认应用B的Angular代码里的请求地址是否写错,改为http://localhost:8083/MYURL后重新测试。

2. 验证后端CSP响应头是否生效

用Chrome开发者工具的「Network」标签,找到应用B调用应用A的API请求,查看响应头中的Content-Security-Policy字段:

  • 如果该字段不存在,或者值仍是default-src 'self',说明你的SecurityConfiguration.java修改未生效,需:
    • 确保应用A完全重启,Spring配置修改后必须重启应用才能生效。
    • 检查配置文件覆盖:JHipster默认从application.yml或application-dev.yml中的security.content-security-policy配置项读取CSP规则,若该配置项存在,会覆盖代码中的硬编码设置,需同步修改或删除该配置项。

3. 检查前端是否设置了CSP

JHipster可能在应用B的src/main/webapp/index.html中添加了<meta http-equiv="Content-Security-Policy">标签,前端CSP会与后端CSP合并生效。若该meta标签内仍是default-src 'self',会导致报错,需修改为对应允许策略或暂时移除测试。

4. 补充CORS配置(额外必要操作)

即使CSP配置正确,跨域请求仍需CORS支持,可在应用A中通过两种方式配置:

  • 局部配置:在新增的API控制器类上添加注解
    @CrossOrigin(origins = "http://localhost:8080")
    
  • 全局配置:在SecurityConfiguration.java中添加CORS配置
    http
        .cors(cors -> cors.configurationSource(corsConfigurationSource()))
        // 保留原有其他配置...
    
    // 定义CORS配置源
    private CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(List.of("http://localhost:8080"));
        configuration.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE", "OPTIONS"));
        configuration.setAllowedHeaders(List.of("*"));
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }
    

内容的提问来源于stack exchange,提问作者Harper2021

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 10:17:40