即使将视图设置为@ xframe_options_exempt,xframe选项仍拒绝Django iframe加载

时间:2018-08-22 17:01:51

标签: django x-frame-options django-middleware clickjacking

我有一个Django应用,我想在其中将一个embed视图作为iframe嵌入到任何网站上。以为我已正确配置了此设置,因为我将视图设置为@xframe_options_exempt,但在Chrome和Firefox中仍然出现X帧选项错误。

Chrome浏览器:Refused to display 'https://foo.com/embed/...' in a frame because it set 'X-Frame-Options' to 'deny'.

Firefox:Load denied by X-Frame-Options: 'https://foo.com/embed/...' does not allow framing

views.py

from django.shortcuts import render, get_object_or_404, redirect
from django.views.decorators.clickjacking import xframe_options_exempt

    @xframe_options_exempt
    def embed(request, bar_slug, slug):
        embed_object = get_object_or_404(foo, slug=slug)

        if embed_object.bar.slug != bar_slug:
           raise Http404

        embed_url = '{}{}'.format('https://foo.com/embed', embed_object.get_absolute_url())

        context = {
            'embed_object': embed_object,
            'embed_url': embed_url,
            'embed_url_encode': urlquote_plus(embed_url),
    }

        return render(request, 'causes/embed.html', context)

settings.py

MIDDLEWARE_CLASSES = [
    'djangosecure.middleware.SecurityMiddleware',
    'project.utils.middleware.SiteMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'corsheaders.middleware.CorsMiddleware',
    'project.utils.middleware.HoneypotMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

我假设djangosecure.middleware.SecurityMiddleware@xframe_options_exempt上强制执行“ X-Frame-Options”。我宁愿使用针对特定视图的解决方案来解决此问题,而不要设置X_FRAME_OPTIONS = 'ALLOW'。谢谢

1 个答案:

答案 0 :(得分:0)

我通过在embed视图中使用两个装饰器来使其工作:

from djangosecure.decorators import frame_deny_exempt
from django.views.decorators.clickjacking import xframe_options_exempt

@xframe_options_exempt
@frame_deny_exempt
def embed(...)

我没有django安全的装饰器。

https://django-secure.readthedocs.io/en/v0.1.1/middleware.html