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

fetch请求未发送(CSP问题):Jenkins页面调用Flask接口失败

问题描述

Jenkins任务生成的网页构建产物需要向Flask应用发送POST请求,尝试添加各类CSP规则(甚至完全放开限制),但浏览器似乎完全忽略这些规则。个人浏览器配置文件下请求正常,但工作配置文件及其他用户环境下均失败。

请求代码

function getNamespaces(cls) {
  const data = {
    cluster: cls,
    username: "${CRED_USERNAME}",
    password: "${CRED_PASSWORD}",
  };

  const requestOptions = {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Content-Security-Policy': "default-src 'unsafe-inline' *; connect-src 'unsafe-inline' *; script-src 'unsafe-inline' *;"
    },
    body: JSON.stringify(data)
  };

  return fetch('http://ilde97192.eaas.mycompany.com:5000/getNamespacesByCluster', requestOptions)
    .then(response => { ......

尝试过的meta标签

<meta http-equiv="Content-Security-Policy" content="default-src 'unsafe-inline' *; connect-src 'unsafe-inline' *; script-src 'unsafe-inline' *;">

Flask应用代码

app = Flask(__name__)
CORS(app, resources={r"/*": {"origins": "*"}})

@app.route("/getNamespacesByCluster", methods=["POST"])
@cross_origin()
def getNamespacesByCluster():
    data = request.get_json()
    cluster = data['cluster']
    username = data['username']
    password = data['password']
    namespacesOutput = f"""
      login=$(oc login "api.{cluster}.ocpd.corp.mycompany.com:6443" -u={username} -p={password} --insecure-skip-tls-verify=true) && echo "[SUCCESS] Cluster connection established." || (echo "[ERROR] Cluster connection failed."; exit 1 > /dev/null; )
      pods=$(oc get pods --all-namespaces -l couchbase_node | awk {{'print $1'}} | awk 'NR>1') && echo "[SUCCESS] Namespaces retrieved successfully." || (echo "[ERROR] Failed to fetch namespaces."; exit 1 > /dev/null; )
      echo $pods
    """
    
    def generate_output():
        with app.app_context():
            command = subprocess.Popen(["bash", "-c", namespacesOutput], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
            for line in iter(command.stdout.readline, b''):
                yield line.rstrip() + b'\n'

    namespaces = generate_output()
    response = Response(stream_with_context(namespaces), mimetype='text/event-stream')
    return response

报错信息

BuildReport.html:664 Refused to connect to
'http://ilde97192.eaas.mycompany.com:5000/getNamespacesByCluster' 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.


解决方案

问题根源

浏览器报错显示生效的CSP是default-src 'self',说明你添加的meta标签和请求头里的CSP规则根本没生效——实际生效的是Jenkins服务器返回的CSP响应头,它覆盖了你页面里的所有设置。

解决步骤

  1. 检查Jenkins当前CSP配置

    • 登录Jenkins后台,进入「Manage Jenkins」→「Script Console」
    • 执行以下Groovy命令查看当前设置:
      println(System.getProperty("hudson.model.DirectoryBrowserSupport.CSP"))
      
    • 若输出为default-src 'self',则确认问题源于此。
  2. 临时修改Jenkins CSP规则

    • 在Script Console执行命令,设置允许访问Flask接口的规则:
      System.setProperty("hudson.model.DirectoryBrowserSupport.CSP", "default-src 'self' http://ilde97192.eaas.mycompany.com:5000; connect-src 'self' http://ilde97192.eaas.mycompany.com:5000; script-src 'unsafe-inline' 'self'; style-src 'unsafe-inline' 'self'")
      
    • 测试环境可临时完全放开:
      System.setProperty("hudson.model.DirectoryBrowserSupport.CSP", "default-src *; connect-src *; script-src 'unsafe-inline' *; style-src 'unsafe-inline' *")
      
  3. 永久生效配置

    • Jenkins重启后临时设置会失效,需修改Jenkins启动参数,在JAVA_OPTS中添加:
      -Dhudson.model.DirectoryBrowserSupport.CSP="default-src 'self' http://ilde97192.eaas.mycompany.com:5000; connect-src 'self' http://ilde97192.eaas.mycompany.com:5000; script-src 'unsafe-inline' 'self'"
      
  4. 清理无效设置

    • 删除请求头里的Content-Security-Policy字段:该字段是响应头字段,浏览器不会处理请求头中的CSP规则。
    • 页面meta标签可保留,但优先级低于服务器响应头,核心还是要修改Jenkins的CSP配置。
  5. 验证效果

    • 重新运行Jenkins任务生成网页,用浏览器开发者工具查看网页请求的响应头,确认Content-Security-Policy为你设置的规则。
    • 再次测试POST请求,即可正常访问Flask接口。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 19:10:45