博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Django Rest Framework remove csrf
阅读量:6266 次
发布时间:2019-06-22

本文共 3846 字,大约阅读时间需要 12 分钟。

 

37
14

I know that there are answers regarding Django Rest Framework, but I couldn't find a solution to my problem.

I have an application which has authentication and some functionality. I added a new app to it, which uses Django Rest Framework. I want to use the library only in this app. Also I want to make POST request, and I always receive this response:

{    "detail": "CSRF Failed: CSRF token missing or incorrect."}

I have the following code:

# urls.pyfrom django.conf.urls import patterns, urlurlpatterns = patterns(    'api.views',    url(r'^object/$', views.Object.as_view()),)# views.pyfrom rest_framework.views import APIViewfrom rest_framework.response import Responsefrom django.views.decorators.csrf import csrf_exemptclass Object(APIView):    @csrf_exempt    def post(self, request, format=None):        return Response({'received data': request.data})

I want add the API without affecting the current application. So my questions is how can I disable CSRF only for this app ?

 
    
You are already using @csrf_exempt token. You can use this on the whole view. Shouldn't that work? –  Jun 16 '15 at 14:55
    
No, I still got the detail: "CSRF Failed: CSRF token missing or incorrect." message. I concluded from the answers that I should remove the default authentication. –  Jun 17 '15 at 6:04
1  
I was running into a VERY similar situation using Token authentication. For anyone else in the same boat: –  Jan 17 '16 at 10:13

6 Answers

71accepted

Why this error is happening?

This is happening because of the default SessionAuthentication scheme used by DRF. DRF's SessionAuthentication uses Django's session framework for authentication which requires CSRF to be checked.

When you don't define any authentication_classes in your view/viewset, DRF uses this authentication classes as the default.

'DEFAULT_AUTHENTICATION_CLASSES'= (    'rest_framework.authentication.SessionAuthentication',    'rest_framework.authentication.BasicAuthentication'),

Since DRF needs to support both session and non-session based authentication to the same views, it enforces CSRF check for only authenticated users. This means that only authenticated requests require CSRF tokens and anonymous requests may be sent without CSRF tokens.

If you're using an AJAX style API with SessionAuthentication, you'll need to include a valid CSRF token for any "unsafe" HTTP method calls, such as PUT, PATCH, POST or DELETE requests.

What to do then?

Now to disable csrf check, you can create a custom authentication class CsrfExemptSessionAuthentication which extends from the default SessionAuthentication class. In this authentication class, we will override the enforce_csrf() check which was happening inside the actual SessionAuthentication.

from rest_framework.authentication import SessionAuthentication class CsrfExemptSessionAuthentication(SessionAuthentication):    def enforce_csrf(self, request):        return  # To not perform the csrf check previously happening

In your view, then you can define the authentication_classes to be:

authentication_classes = (CsrfExemptSessionAuthentication, BasicAuthentication)

This should handle the csrf error.

 
    
Thanks, great answer. There should be a built in way to do this in restframework, but currently this is the best solution I found. –  Oct 13 '15 at 14:06
1  
Thank you, it worked! with Django 1.9 –  Apr 17 '16 at 21:01
1  
Sorry maybe I missed the point, but isn't a security risk to bypass/disable the csrf protection? –  Feb 5 at 18:37
1  
@Paolo OP needed to disable the CSRF authentication for a particular API. But yes, its a security risk to disable the csrf protection. If one needs to disable session authentication for a particular use case, then he can use this solution. –  Feb 6 at 6:09 

转载于:https://www.cnblogs.com/AmilyWilly/p/6438448.html

你可能感兴趣的文章
ant重新编译打包hadoop-core-1.2.1.jar时遇到的错
查看>>
【★★★★★】提高PHP代码质量的36个技巧
查看>>
3 weekend110的配置hadoop(格式化) + 一些问题解决 + 未免密码配置
查看>>
JavaScript Creating 对象
查看>>
Java compiler level does not match the version of the installed Java project facet.(转)
查看>>
WPF MediaElement.Position属性
查看>>
sqoop数据迁移(基于Hadoop和关系数据库服务器之间传送数据)
查看>>
spring mysql多数据源配置
查看>>
[React] Override webpack config for create-react-app without ejection
查看>>
检索 COM 类工厂中 CLSID 为{00024500-0000-0000-C000-000000000046} 的组件时失败,原因是出现以下错误: 80070005。...
查看>>
测试java的父子类化
查看>>
HDOJ 1008
查看>>
安装thrift出现的一些问题
查看>>
makefile编写---单个子目录编译模板
查看>>
Oracle DB_LINK如何使用
查看>>
cv resource
查看>>
关于加快INSERT语句执行速度和HINT /*+ append */及/*+ append nologging */的使用
查看>>
JDK源代码学习系列07----Stack
查看>>
firefox
查看>>
PS批处理的使用
查看>>