Chrome cloudflare可以添加自定义标题吗?

nfs0ujit  于 2023-03-16  发布在  Go
关注(0)|答案(2)|浏览(153)

有没有办法在cloudflare中添加自定义标题?
我们有一些https AJAX 来缓存静态文件,但是它不能处理响应头中的“Access-Control-Allow-Credentials”这样的头,这会导致chrome失败。

n7taea2i

n7taea2i1#

Scott海尔姆已经发布了一种使用最近发布的Cloudflare Workers来实现这一点的方法。
https://scotthelme.co.uk/security-headers-cloudflare-worker/

let securityHeaders = {
  "Content-Security-Policy": "upgrade-insecure-requests",
  "Strict-Transport-Security": "max-age=1000",
  "X-Xss-Protection": "1; mode=block",
  "X-Frame-Options": "DENY",
  "X-Content-Type-Options": "nosniff",
  "Referrer-Policy": "strict-origin-when-cross-origin",
}

let sanitiseHeaders = {
  "Server": "My New Server Header!!!",
}

let removeHeaders = [
  "Public-Key-Pins",
  "X-Powered-By",
  "X-AspNet-Version",
]

addEventListener('fetch', event => {
  event.respondWith(addHeaders(event.request))
})

async function addHeaders(req) {
  let response = await fetch(req)
  let newHdrs = new Headers(response.headers)

  if (newHdrs.has("Content-Type") && !newHdrs.get("Content-Type").includes("text/html")) {
    return new Response(response.body, {
      status: response.status,
      statusText: response.statusText,
      headers: newHdrs
    })
  }

  Object.keys(securityHeaders).map(function(name, index) {
    newHdrs.set(name, securityHeaders[name]);
  })

  Object.keys(sanitiseHeaders).map(function(name, index) {
    newHdrs.set(name, sanitiseHeaders[name]);
  })

  removeHeaders.forEach(function(name) {
    newHdrs.delete(name)
  })

  return new Response(response.body, {
    status: response.status,
    statusText: response.statusText,
    headers: newHdrs
  })
}
kgsdhlau

kgsdhlau2#

要添加自定义标题,请在Cloudflare中选择Workers

要添加Access-Control-Allow-CredentialsX-Frame-Options等自定义头文件,请添加以下小脚本:-

addEventListener('fetch', event => {
  event.respondWith(handleRequest(event.request))
})

async function handleRequest(request) {
  let response = await fetch(request)
  let newHeaders = new Headers(response.headers)
  newHeaders.set("Access-Control-Allow-Credentials", "true")
  newHeaders.set("X-Frame-Options", "SAMEORIGIN")
  
  // ... and any more required headers

  return new Response(response.body, {
    status: response.status,
    statusText: response.statusText,
    headers: newHeaders
  })
}

创建员工后,您需要将其与路线匹配,例如

如果您现在使用Chrome开发工具等工具测试端点,您将看到响应头。

相关问题