110

我有一个 ASP.NET 4.0 IIS7.5 站点,我需要使用 X-Frame-Options 标头对其进行保护。

我还需要使我的网站页面能够从我的同一个域以及我的 facebook 应用程序中进行 iframe。

目前,我的站点配置了以下站点:

Response.Headers.Add("X-Frame-Options", "ALLOW-FROM SAMEDOMAIN, www.facebook.com/MyFBSite")

当我使用 Chrome 或 Firefox 查看我的 Facebook 页面时,我的网站页面(使用我的 Facebook 页面进行 iframe)显示正常,但在 IE9 下,我收到错误消息:

“此页面无法显示……”(由于X-Frame_Options限制)。

如何设置X-Frame-Options: ALLOW-FROM支持多个域?

X-FRAME-OPTION如果只能定义一个域,那么作为一项新功能似乎存在根本缺陷。

4

12 回答 12

119

X-Frame-Options已弃用。来自MDN

此功能已从 Web 标准中删除。尽管某些浏览器可能仍然支持它,但它正在被删除。不要在旧项目或新项目中使用它。使用它的页面或 Web 应用程序可能随时中断。

现代替代方案是标头,它与许多其他策略一起可以使用该指令Content-Security-Policy将允许在框架中托管您的页面的 URL 列入白名单。支持多个域甚至通配符,例如:frame-ancestors
frame-ancestors

Content-Security-Policy: frame-ancestors 'self' example.com *.example.net ;

不幸的是,目前,Internet Explorer 并不完全支持 Content-Security-Policy

更新: MDN 删除了他们的弃用评论。这是W3C 的内容安全策略级别的类似评论

frame-ancestors指令废弃X-Frame-Options标头。如果一个资源同时具有这两种策略,则frame-ancestors应该强制执行该X-Frame-Options策略并且应该忽略该策略。

于 2014-09-02T07:06:19.283 回答
41

来自RFC 7034

不允许使用通配符或列表在一个 ALLOW-FROM 语句中声明多个域

所以,

如何设置 X-Frame-Options: ALLOW-FROM 以支持多个域?

你不能。作为一种解决方法,您可以为不同的合作伙伴使用不同的 URL。对于每个 URL,您可以使用它自己的X-Frame-Options值。例如:

partner   iframe URL       ALLOW-FROM
---------------------------------------
Facebook  fb.yoursite.com  facebook.com
VK.COM    vk.yoursite.com  vk.com

因为yousite.com你可以使用X-Frame-Options: deny.

顺便说一句,目前 Chrome(以及所有基于 webkit 的浏览器)根本不支持 ALLOW-FROM语句。

于 2014-01-24T09:57:25.170 回答
10

死灵术。
提供的答案不完整。

首先,如前所述,您不能添加多个允许主机,这是不受支持的。
其次,您需要从 HTTP 引荐来源网址动态提取该值,这意味着您不能将该值添加到 Web.config,因为它并不总是相同的值。

当浏览器是 Chrome 时,有必要进行浏览器检测以避免添加 allow-from(它会在调试 - 控制台上产生错误,这可以快速填满控制台,或使应用程序变慢)。这也意味着您需要修改 ASP.NET 浏览器检测,因为它错误地将 Edge 识别为 Chrome。

这可以在 ASP.NET 中通过编写一个在每个请求上运行的 HTTP 模块来完成,该模块为每个响应附加一个 http 标头,具体取决于请求的引用者。对于 Chrome,需要添加 Content-Security-Policy。

// https://stackoverflow.com/questions/31870789/check-whether-browser-is-chrome-or-edge
public class BrowserInfo
{

    public System.Web.HttpBrowserCapabilities Browser { get; set; }
    public string Name { get; set; }
    public string Version { get; set; }
    public string Platform { get; set; }
    public bool IsMobileDevice { get; set; }
    public string MobileBrand { get; set; }
    public string MobileModel { get; set; }


    public BrowserInfo(System.Web.HttpRequest request)
    {
        if (request.Browser != null)
        {
            if (request.UserAgent.Contains("Edge")
                && request.Browser.Browser != "Edge")
            {
                this.Name = "Edge";
            }
            else
            {
                this.Name = request.Browser.Browser;
                this.Version = request.Browser.MajorVersion.ToString();
            }
            this.Browser = request.Browser;
            this.Platform = request.Browser.Platform;
            this.IsMobileDevice = request.Browser.IsMobileDevice;
            if (IsMobileDevice)
            {
                this.Name = request.Browser.Browser;
            }
        }
    }


}


void context_EndRequest(object sender, System.EventArgs e)
{
    if (System.Web.HttpContext.Current != null && System.Web.HttpContext.Current.Response != null)
    {
        System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;

        try
        {
            // response.Headers["P3P"] = "CP=\\\"IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT\\\"":
            // response.Headers.Set("P3P", "CP=\\\"IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT\\\"");
            // response.AddHeader("P3P", "CP=\\\"IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT\\\"");
            response.AppendHeader("P3P", "CP=\\\"IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT\\\"");

            // response.AppendHeader("X-Frame-Options", "DENY");
            // response.AppendHeader("X-Frame-Options", "SAMEORIGIN");
            // response.AppendHeader("X-Frame-Options", "AllowAll");

            if (System.Web.HttpContext.Current.Request.UrlReferrer != null)
            {
                // "X-Frame-Options": "ALLOW-FROM " Not recognized in Chrome 
                string host = System.Web.HttpContext.Current.Request.UrlReferrer.Scheme + System.Uri.SchemeDelimiter
                            + System.Web.HttpContext.Current.Request.UrlReferrer.Authority
                ;

                string selfAuth = System.Web.HttpContext.Current.Request.Url.Authority;
                string refAuth = System.Web.HttpContext.Current.Request.UrlReferrer.Authority;

                // SQL.Log(System.Web.HttpContext.Current.Request.RawUrl, System.Web.HttpContext.Current.Request.UrlReferrer.OriginalString, refAuth);

                if (IsHostAllowed(refAuth))
                {
                    BrowserInfo bi = new BrowserInfo(System.Web.HttpContext.Current.Request);

                    // bi.Name = Firefox
                    // bi.Name = InternetExplorer
                    // bi.Name = Chrome

                    // Chrome wants entire path... 
                    if (!System.StringComparer.OrdinalIgnoreCase.Equals(bi.Name, "Chrome"))
                        response.AppendHeader("X-Frame-Options", "ALLOW-FROM " + host);    

                    // unsafe-eval: invalid JSON https://github.com/keen/keen-js/issues/394
                    // unsafe-inline: styles
                    // data: url(data:image/png:...)

                    // https://www.owasp.org/index.php/Clickjacking_Defense_Cheat_Sheet
                    // https://www.ietf.org/rfc/rfc7034.txt
                    // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Frame-Options
                    // https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP

                    // https://stackoverflow.com/questions/10205192/x-frame-options-allow-from-multiple-domains
                    // https://content-security-policy.com/
                    // http://rehansaeed.com/content-security-policy-for-asp-net-mvc/

                    // This is for Chrome:
                    // response.AppendHeader("Content-Security-Policy", "default-src 'self' 'unsafe-inline' 'unsafe-eval' data: *.msecnd.net vortex.data.microsoft.com " + selfAuth + " " + refAuth);


                    System.Collections.Generic.List<string> ls = new System.Collections.Generic.List<string>();
                    ls.Add("default-src");
                    ls.Add("'self'");
                    ls.Add("'unsafe-inline'");
                    ls.Add("'unsafe-eval'");
                    ls.Add("data:");

                    // http://az416426.vo.msecnd.net/scripts/a/ai.0.js

                    // ls.Add("*.msecnd.net");
                    // ls.Add("vortex.data.microsoft.com");

                    ls.Add(selfAuth);
                    ls.Add(refAuth);

                    string contentSecurityPolicy = string.Join(" ", ls.ToArray());
                    response.AppendHeader("Content-Security-Policy", contentSecurityPolicy);
                }
                else
                {
                    response.AppendHeader("X-Frame-Options", "SAMEORIGIN");
                }

            }
            else
                response.AppendHeader("X-Frame-Options", "SAMEORIGIN");
        }
        catch (System.Exception ex)
        {
            // WTF ? 
            System.Console.WriteLine(ex.Message); // Suppress warning
        }

    } // End if (System.Web.HttpContext.Current != null && System.Web.HttpContext.Current.Response != null)

} // End Using context_EndRequest


private static string[] s_allowedHosts = new string[] 
{
     "localhost:49533"
    ,"localhost:52257"
    ,"vmcompany1"
    ,"vmcompany2"
    ,"vmpostalservices"
    ,"example.com"
};


public static bool IsHostAllowed(string host)
{
    return Contains(s_allowedHosts, host);
} // End Function IsHostAllowed 


public static bool Contains(string[] allowed, string current)
{
    for (int i = 0; i < allowed.Length; ++i)
    {
        if (System.StringComparer.OrdinalIgnoreCase.Equals(allowed[i], current))
            return true;
    } // Next i 

    return false;
} // End Function Contains 

您需要在 HTTP-module Init 函数中注册 context_EndRequest 函数。

public class RequestLanguageChanger : System.Web.IHttpModule
{


    void System.Web.IHttpModule.Dispose()
    {
        // throw new NotImplementedException();
    }


    void System.Web.IHttpModule.Init(System.Web.HttpApplication context)
    {
        // https://stackoverflow.com/questions/441421/httpmodule-event-execution-order
        context.EndRequest += new System.EventHandler(context_EndRequest);
    }

    // context_EndRequest Code from above comes here


}

接下来,您需要将模块添加到您的应用程序中。您可以在 Global.asax 中通过重写 HttpApplication 的 Init 函数以编程方式执行此操作,如下所示:

namespace ChangeRequestLanguage
{


    public class Global : System.Web.HttpApplication
    {

        System.Web.IHttpModule mod = new libRequestLanguageChanger.RequestLanguageChanger();

        public override void Init()
        {
            mod.Init(this);
            base.Init();
        }



        protected void Application_Start(object sender, System.EventArgs e)
        {

        }

        protected void Session_Start(object sender, System.EventArgs e)
        {

        }

        protected void Application_BeginRequest(object sender, System.EventArgs e)
        {

        }

        protected void Application_AuthenticateRequest(object sender, System.EventArgs e)
        {

        }

        protected void Application_Error(object sender, System.EventArgs e)
        {

        }

        protected void Session_End(object sender, System.EventArgs e)
        {

        }

        protected void Application_End(object sender, System.EventArgs e)
        {

        }


    }


}

或者,如果您不拥有应用程序源代码,则可以将条目添加到 Web.config:

      <httpModules>
        <add name="RequestLanguageChanger" type= "libRequestLanguageChanger.RequestLanguageChanger, libRequestLanguageChanger" />
      </httpModules>
    </system.web>

  <system.webServer>
    <validation validateIntegratedModeConfiguration="false"/>

    <modules runAllManagedModulesForAllRequests="true">
      <add name="RequestLanguageChanger" type="libRequestLanguageChanger.RequestLanguageChanger, libRequestLanguageChanger" />
    </modules>
  </system.webServer>
</configuration>

system.webServer 中的条目适用于 IIS7+,system.web 中的另一个条目适用于 IIS 6。
请注意,您需要将 runAllManagedModulesForAllRequests 设置为 true,才能正常工作。

type 中的字符串格式为"Namespace.Class, Assembly". 请注意,如果您在 VB.NET 而不是 C# 中编写程序集,VB 将为每个项目创建一个默认命名空间,因此您的字符串看起来像

"[DefaultNameSpace.Namespace].Class, Assembly"

如果要避免此问题,请用 C# 编写 DLL。

于 2017-04-10T12:26:01.367 回答
7

一种不仅允许多个域,而且允许动态域的方法怎么样?

这里的用例是一个 Sharepoint 应用程序部分,它通过 iframe 在 Sharepoint 内加载我们的网站。问题是 sharepoint 具有动态子域,例如https://yoursite.sharepoint.com。所以对于 IE,我们需要指定 ALLOW-FROM https://.sharepoint.com

棘手的业务,但我们可以在知道两个事实的情况下完成它:

  1. 当 iframe 加载时,它仅在第一个请求时验证 X-Frame-Options。加载 iframe 后,您可以在 iframe 内导航,并且不会在后续请求中检查标头。

  2. 此外,当加载 iframe 时,HTTP 引用者是父 iframe url。

您可以在服务器端利用这两个事实。在 ruby​​ 中,我使用以下代码:

  uri = URI.parse(request.referer)
  if uri.host.match(/\.sharepoint\.com$/)
    url = "https://#{uri.host}"
    response.headers['X-Frame-Options'] = "ALLOW-FROM #{url}"
  end

在这里,我们可以根据父域动态地允许域。在这种情况下,我们确保主机以 sharepoint.com 结尾,以确保我们的网站免受点击劫持。

我很想听听有关这种方法的反馈。

于 2015-11-03T03:16:02.510 回答
4

根据MDN 规范X-Frame-Options: ALLOW-FROMChrome 不支持,Edge 和 Opera 中的支持未知。

Content-Security-Policy: frame-ancestors覆盖X-Frame-Options(根据此 W3 规范),但frame-ancestors兼容性有限。根据这些MDN Specs,IE 或 Edge 不支持它。

于 2017-08-24T23:40:45.257 回答
2

严格来说不,你不能。

但是,您可以指定X-Frame-Options: mysite.com并因此允许subdomain1.mysite.comand subdomain2.mysite.com。但是,是的,这仍然是一个域。碰巧有一些解决方法,但我认为直接在 RFC 规范中阅读它是最容易的:https ://www.rfc-editor.org/rfc/rfc7034

还值得指出的是,Content-Security-Policy (CSP) 标头的frame-ancestor指令已经过时了 X-Frame-Options。在这里阅读更多

于 2019-09-27T09:47:42.213 回答
2

HTTP 标头字段 X-Frame-Options的 RFC规定 X-Frame-Options 标头值中的“ALLOW-FROM”字段只能包含一个域。不允许多个域。

RFC 建议解决此问题。解决方法是在iframe src url中指定域名作为url参数。托管 iframe src url 的服务器然后可以检查 url 参数中给出的域名。如果域名与有效域名列表匹配,则服务器可以发送 X-Frame-Options 标头,其值为:“ALLOW-FROM domain-name”,其中 domain name 是尝试访问的域的名称嵌入远程内容。如果域名未给出或无效,则可以发送 X-Frame-Options 标头,其值为:“deny”。

于 2019-09-25T12:42:26.060 回答
0

不完全相同,但可以在某些情况下工作:还有另一个选项ALLOWALL可以有效地消除限制,这对于测试/预生产环境可能是一件好事

于 2017-01-04T09:59:50.507 回答
0

Apache适用于多个域和子域的规则.htaccess如下:

Header always append Content-Security-Policy "frame-ancestors 'self' site1 site2;"

例子:

下面的规则将只允许yoursite (self),https://example1.com/https://example2.com放置iFrameyoursite

Header always append Content-Security-Policy "frame-ancestors 'self' https://example1.com/ https://example.com;"

这是参考链接

于 2021-12-20T17:42:18.557 回答
0

我必须为 IE 添加 X-Frame-Options 和为其他浏览器添加 Content-Security-Policy。所以我做了类似以下的事情。

if allowed_domains.present?
  request_host = URI.parse(request.referer)
  _domain = allowed_domains.split(" ").include?(request_host.host) ? "#{request_host.scheme}://#{request_host.host}" : app_host
  response.headers['Content-Security-Policy'] = "frame-ancestors #{_domain}"
  response.headers['X-Frame-Options'] = "ALLOW-FROM #{_domain}"
else
  response.headers.except! 'X-Frame-Options'
end
于 2018-10-01T07:49:53.300 回答
-4

一种可能的解决方法是使用此处描述的“帧中断”脚本

您只需要更改“if”语句即可检查您允许的域。

   if (self === top) {
       var antiClickjack = document.getElementById("antiClickjack");
       antiClickjack.parentNode.removeChild(antiClickjack);
   } else {
       //your domain check goes here
       if(top.location.host != "allowed.domain1.com" && top.location.host == "allowed.domain2.com")
         top.location = self.location;
   }

我认为这种解决方法是安全的。因为如果未启用 javascript,您将不会担心恶意网站构建您的页面。

于 2014-02-20T06:54:43.647 回答
-9

是的。此方法允许多个域。

VB.NET

response.headers.add("X-Frame-Options", "ALLOW-FROM " & request.urlreferer.tostring())
于 2015-04-11T20:34:10.303 回答