Python 如何禁用 Django 的 CSRF 验证?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16458166/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to disable Django's CSRF validation?
提问by WoooHaaaa
I have commented out csrf processor and middleware lines in settings.py:
我已经注释掉了 csrf 处理器和中间件行settings.py:
122
123 TEMPLATE_CONTEXT_PROCESSORS = (
124 'django.contrib.auth.context_processors.auth',
125 # 'django.core.context_processors.csrf',
126 'django.core.context_processors.request',
127 'django.core.context_processors.static',
128 'cyathea.processors.static',
129 )
130
131 MIDDLEWARE_CLASSES = (
132 'django.middleware.common.CommonMiddleware',
133 'django.contrib.sessions.middleware.SessionMiddleware',
134 # 'django.middleware.csrf.CsrfViewMiddleware',
135 'django.contrib.auth.middleware.AuthenticationMiddleware',
136 'django.contrib.messages.middleware.MessageMiddleware',
137 'django.middleware.locale.LocaleMiddleware',
138 # Uncomment the next line for simple clickHymaning protection:
139 # 'django.middleware.clickHymaning.XFrameOptionsMiddleware',
140 )
But when I use Ajax to send a request, Django still respond 'csrf token is incorrect or missing', and after adding X-CSRFToken to headers, the request would succeed.
但是当我使用 Ajax 发送请求时,Django 仍然响应“csrf token 不正确或丢失”,并且将 X-CSRFToken 添加到标头后,请求会成功。
What is going on here ?
这里发生了什么 ?
回答by Salvatorelab
If you just need some views not to use CSRF, you can use @csrf_exempt:
如果你只需要一些不使用 CSRF 的视图,你可以使用@csrf_exempt:
from django.views.decorators.csrf import csrf_exempt
@csrf_exempt
def my_view(request):
return HttpResponse('Hello world')
You can find more examples and other scenarios in the Django documentation:
您可以在 Django 文档中找到更多示例和其他场景:
回答by s29
CSRF can be enforced at the view level, which can't be disabled globally.
CSRF 可以在视图级别强制执行,不能全局禁用。
In some cases this is a pain, but um, "it's for security". Gotta retain those AAA ratings.
在某些情况下,这是一种痛苦,但嗯,“这是为了安全”。必须保留那些AAA评级。
https://docs.djangoproject.com/en/dev/ref/csrf/#contrib-and-reusable-apps
https://docs.djangoproject.com/en/dev/ref/csrf/#contrib-and-reusable-apps
回答by naren
The answer might be inappropriate, but I hope it helps you
答案可能不恰当,但希望对您有所帮助
class DisableCSRFOnDebug(object):
def process_request(self, request):
if settings.DEBUG:
setattr(request, '_dont_enforce_csrf_checks', True)
Having middleware like this helps to debug requests and to check csrf in production servers.
拥有这样的中间件有助于调试请求并检查生产服务器中的 csrf。
回答by Martijn ten Hoor
To disable CSRF for class based views the following worked for me.
Using django 1.10 and python 3.5.2
要为基于类的视图禁用 CSRF,以下对我有用。
使用 django 1.10 和 python 3.5.2
from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decorator
@method_decorator(csrf_exempt, name='dispatch')
class TestView(View):
def post(self, request, *args, **kwargs):
return HttpResponse('Hello world')
回答by Rohit33
In setting.pyin MIDDLEWARE you can simply remove/comment this line:
在setting.pyMIDDLEWARE 中,您可以简单地删除/注释此行:
'django.middleware.csrf.CsrfViewMiddleware',
回答by JJP
If you want disable it in Global, you can write a custom middleware, like this
如果你想在 Global 中禁用它,你可以编写一个自定义的中间件,像这样
from django.utils.deprecation import MiddlewareMixin
class DisableCsrfCheck(MiddlewareMixin):
def process_request(self, req):
attr = '_dont_enforce_csrf_checks'
if not getattr(req, attr, False):
setattr(req, attr, True)
then add this class youappname.middlewarefilename.DisableCsrfCheckto MIDDLEWARE_CLASSESlists, before django.middleware.csrf.CsrfViewMiddleware
然后将此类添加youappname.middlewarefilename.DisableCsrfCheck到MIDDLEWARE_CLASSES列表之前django.middleware.csrf.CsrfViewMiddleware
回答by Madhuri Gole
The problem here is that SessionAuthentication performs its own CSRF validation. That is why you get the CSRF missing error even when the CSRF Middleware is commented. You could add @csrf_exempt to every view, but if you want to disable CSRF and have session authentication for the whole app, you can add an extra middleware like this -
这里的问题是 SessionAuthentication 执行自己的 CSRF 验证。这就是为什么即使在评论 CSRF 中间件时也会出现 CSRF 丢失错误的原因。您可以将 @csrf_exempt 添加到每个视图,但如果您想禁用 CSRF 并为整个应用程序进行会话身份验证,您可以添加一个额外的中间件,如下所示 -
class DisableCSRFMiddleware(object):
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
setattr(request, '_dont_enforce_csrf_checks', True)
response = self.get_response(request)
return response
I created this class in myapp/middle.py Then import this middleware in Middleware in settings.py
我在 myapp/middle.py 中创建了这个类然后在 settings.py 的 Middleware 中导入这个中间件
MIDDLEWARE = [
'django.middleware.common.CommonMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
#'django.middleware.csrf.CsrfViewMiddleware',
'myapp.middle.DisableCSRFMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickHymaning.XFrameOptionsMiddleware',
]
That works with DRF on django 1.11
这适用于 django 1.11 上的 DRF
回答by Fran?ois Constant
For Django 2:
对于Django 2:
from django.utils.deprecation import MiddlewareMixin
class DisableCSRF(MiddlewareMixin):
def process_request(self, request):
setattr(request, '_dont_enforce_csrf_checks', True)
That middleware must be added to settings.MIDDLEWAREwhen appropriate (in your test settings for example).
必须settings.MIDDLEWARE在适当的时候(例如在您的测试设置中)添加该中间件。
Note: the setting isn't not called MIDDLEWARE_CLASSESanymore.
注意:不再调用该设置MIDDLEWARE_CLASSES。

