点击劫持保护

点击劫持是一种恶意技术,它欺骗网络用户点击与用户认为他们点击的内容不同的内容。学到更多

要启用 clickjacking 保护,请将 XFrameOptionsMiddleware 添加到你的中间件类。如果你没有删除它,它应该已经存在。

# settings.py
MIDDLEWARE_CLASSES = [
    ...
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    ...
]

此中间件将“X-Frame-Options”标题设置为你的所有响应,除非明确豁免或已设置(如果已在响应中设置,则不会覆盖)。默认情况下,它设置为 SAMEORIGIN。要更改此设置,请使用 X_FRAME_OPTIONS 设置:

X_FRAME_OPTIONS = 'DENY'

你可以基于每个视图覆盖默认行为。

from django.utils.decorators import method_decorator
from django.views.decorators.clickjacking import (
    xframe_options_exempt, xframe_options_deny, xframe_options_sameorigin,
)

xframe_options_exempt_m = method_decorator(xframe_options_exempt, name='dispatch')

@xframe_options_sameorigin
def my_view(request, *args, **kwargs):
    """Forces 'X-Frame-Options: SAMEORIGIN'."""
    return HttpResponse(...)

@method_decorator(xframe_options_deny, name='dispatch')
class MyView(View):
    """Forces 'X-Frame-Options: DENY'."""

@xframe_options_exempt_m
class MyView(View):
    """Does not set 'X-Frame-Options' header when passing through the
    XFrameOptionsMiddleware.
    """