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

Spring Boot+Angular环境下Content Security Policy未拦截外部JS加载问题

问题描述

我正在使用Spring Boot与Angular进行开发,配置了如下内容安全策略(Content Security Policy):

img-src 'none'; default-src 'none'; font-src 'none'; style-src 'none'; script-src 'none'; 

但在前端控制台中发现,仍有来自外部站点的JS文件被加载,该JS是通过以下Angular代码动态引入的:

ngAfterViewInit() {
  var s = document.createElement("script");
  s.type = "text/javascript";
  s.src = "https://www.google.com/recaptcha/api.js";
  this.elementRef.nativeElement.appendChild(s);
}

为何配置的CSP未拦截该外部JS的加载?

原因分析与解决方案

核心排查方向

  1. CSP未通过HTTP响应头正确生效
    如果你的CSP是通过HTML的<meta>标签配置的,浏览器对这种方式的CSP支持存在局限性——部分场景下不会拦截通过DOM API动态发起的资源请求。正确的做法是通过HTTP响应头Content-Security-Policy发送规则,而非仅依赖meta标签。

  2. 实际生效的CSP与配置不符
    Spring Boot中若存在多渠道配置CSP(如过滤器、Spring Security、控制器注解),可能出现规则被覆盖的情况。你可以通过浏览器开发者工具的「Network」面板,查看页面主请求的响应头,确认Content-Security-Policy字段的内容是否和你预期的一致。

  3. 浏览器临时禁用了CSP
    若开启了浏览器开发者工具的「禁用CSP」选项,会导致规则失效。可以在开发者工具的「Security」面板中查看当前页面的CSP状态,确认规则是否正常加载。

验证与修复步骤

  • 验证CSP生效状态:打开浏览器开发者工具的「Security」面板,查看「Content Security Policy」板块,确认生效规则是否匹配配置。
  • 通过Spring Security配置CSP(推荐):使用HTTP响应头发送CSP规则,示例代码如下:
@Configuration
@EnableWebSecurity
public class SecurityConfig {
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
            .headers(headers -> headers
                .contentSecurityPolicy(csp -> csp
                    .policyDirectives("img-src 'none'; default-src 'none'; font-src 'none'; style-src 'none'; script-src 'none';")
                )
            );
        return http.build();
    }
}
  • 若需加载Recaptcha脚本:修改CSP的script-src规则,添加允许的源,同时根据Recaptcha的需求补充其他规则(如frame-src):
img-src 'none'; default-src 'none'; font-src 'none'; style-src 'none'; script-src 'none' https://www.google.com/recaptcha/; frame-src https://www.google.com/recaptcha/;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 09:40:30