如何创建内容安全策略以允许网站在 iframe 中运行

How to create a Content Security Policy to allow a website to work inside an iframe

我需要第三方网站在我网站的 iframe 内运行。第三方网站在 FireFox 的 iframe 中完美运行。在 Chrome 中,出于某种原因,用户只允许登录,此后他们单击任何 link 都会将他们带回登录页面(这是 iframe 的默认页面)。

所以我寻找了一个解决方案,看来我需要创建一个内容安全策略。我以前从未使用过内容安全策略,所以我不确定该怎么做。

我遇到了一个带有元标记示例的 post,我尝试了其中的几种变体,但无论我如何尝试,在 Chrome 中,页面甚至无法加载iframe.

<html>
<head>
<title>Student Portal</title>
<link rel="shortcut icon" href="favicon.ico">
<meta http-equiv="Content-Security-Policy" content="default-src 'self' https://<third party site>; img-src https://*; child-src 'self' https://<third party site>; script-src 'self' https://<third party site>; style-src 'self' https://<third party site>;" />
</head>
<body>
<!-- rest of my code -->
</body>
</html>

我也尝试了 <embed> 元素,但得到了相同的结果。

是否有另一种创建内容安全策略的方法,或者可能是其他完整的解决方案?

如有任何帮助,我们将不胜感激

尝试为 iframe 添加沙盒属性

<iframe sandbox></iframe>

Content-Security-Policy 无法解决您的问题

Content-Security-Policy (CSP) 只能限制网页中发生的事情并阻止默认打开的行为。

最有可能的问题 - SameSite 或 Sec-fetch headers

您描述的网站允许框架但阻止登录的问题的最可能原因:

选项 1:SameSite 默认 Cookie

如果站点未使用 SameSite 参数显式设置登录 cookie - 这可能是问题所在。 Firefox 默认使用安全性较低的 cookie SameSite=None。 Chrome 默认使用更安全的 cookie SameSite=Lax(某种)。

Lax cookie 最终可能会从框架请求中丢弃(因为它可能是 Clickjacking / CSRF 的一种形式)

选项 2:站点有 Fetch metadata request headers

的服务器端处理程序

根据上下文,该站点可能在 server-side 上被阻止。 这些功能仅在最近发布的 Firefox 90 中受支持,但在 Chrome 中已经有一段时间了。 如果您使用的是 Firefox 90,并且在对该站点的请求中看到 Sec-Fetch header,并且流程正常,那么这不是问题所在。 如果升级到 V90 时它在 FF 中中断 - 类似于 Chrome: 您的问题是其中之一的处理程序:

Sec-Fetch-Site
Sec-Fetch-Mode
Sec-Fetch-User
Sec-Fetch-Dest

选项 3:其他?

在案例/网站上分享更多信息,我会建议更多选项。

相关:CSP 使用示例

默认情况下,您可以在您的站点中构建任何其他站点。这是网络的开放性。 但是,您可以使用 CSP 阻止来自您网站的 iframe:

Content-Security-Policy:frame-src 'none';

同样,站点可以通过设置 X-frame-options:deny:

的(更好的)等价物来拒绝使用 CSP 框架

Content-Security-Policy:frame-ancestors 'none';

P.S。不要使用 CSP 元标记

通过 html 元 header 为 CSP 提供服务被认为是遗留问题,并且在多个浏览器 edge-cases 中存在一些缺点。仅通过请求的 HTTP header 设置 CSP。

More info on <meta> bugs