如何在 Django 中配置 X-Frame-Options 以允许 iframe 嵌入一个视图?

How to configure X-Frame-Options in Django to allow iframe embedding of one view?

我正在尝试启用 django 以允许将一个特定视图嵌入外部站点,最好没有站点限制。

在我的 views.py 文件中,我添加了以下代码,其中视图 futurebig 是我想要的启用嵌入:

from django.views.decorators.clickjacking import xframe_options_sameorigin
...
@xframe_options_sameorigin
def futurebig(request):
    ...
    return render_to_response('templates/iframe/future_clock_big.html', context_dict, context)

据我所知,这没有帮助,因为它只能在同一服务器中嵌入。

如何为该特定视图设置 headers 以使其能够嵌入任何网站?

郑重声明,我只是一名前端开发人员,开发该网站的后端开发人员不再与我合作并拒绝记录他的代码,所以,如果有人能帮助我并仔细解释在哪里和做什么我应该做的修改,我会非常感谢。

谢谢。

据我所知,Django版本是1.6

您正朝着正确的方向前进,但实现此目标所需的确切装饰器是 'xframe_options_exempt'。

from django.http import HttpResponse
from django.views.decorators.clickjacking import xframe_options_exempt

@xframe_options_exempt
def ok_to_load_in_a_frame(request):
    return HttpResponse("This page is safe to load in a frame on any site.")

PS: 不再支持 DJango 1.6。是时候升级了。

显然您可以在您的设置中设置一个规则,说明以下内容:

X_FRAME_OPTIONS = 'ALLOW-FROM https://example.com/'

现在你也应该考虑转向 CSP

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

如果你想在特定视图中允许框架,你可以将 Content-Security-Policy 添加到你的视图响应中,所以你的代码将是这样的

def MyView(request):
    ....
    ....
    response = render(request,'MyViewHtml.html' ,{...})
    response ['Content-Security-Policy'] = "frame-ancestors 'self' https://example.com"