我在我的项目中使用django-1.10,我希望在我的项目中禁用CSRF检查。为此,我创建了一个CSRFDiable中间件,并将其添加到CommonMiddleWare之后的中间件中。在django 1.8中,同样的过程也适用于我,但在django 1.10,这个过程并不有效。我也尝试过删除django.middleware.csrf.CsrfViewMiddleware,但它对我不起作用。中间件类如下所示
class DisableCSRF(object):
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
return self.get_response(request)
def process_request(self, request):
setattr(request, '_dont_enforce_csrf_checks', True)
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'common.middlewares.DisableCSRF',
# 'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]我在POST请求中遇到的错误是
{
"detail": "CSRF Failed: CSRF token missing or incorrect."
}发布于 2017-09-10 17:41:18
在全球范围内禁用csrf protection不是一个好主意。但是,如果您仍然希望禁用基于CSRF的API的rest-framework,那么您可以做的就是重写django-rest-framework的SessionAuthentication类,并将其添加到django-rest-framework DEFAULT_AUTHENTICATION_CLASSES设置中,这样就完成了。你可以这样做
from rest_framework.authentication import SessionAuthentication
class CsrfExemptSessionAuthentication(SessionAuthentication):
def enforce_csrf(self, request):
return # it will not perform any csrf check在您的rest_framework设置中添加
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'path of .CsrfExemptSessionAuthentication', # path of CsrfExemptSessionAuthentication class
'rest_framework.authentication.BasicAuthentication'
),
}我希望它能对你有用
或者你能做的就是使用token base authentication。
https://stackoverflow.com/questions/46141385
复制相似问题