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.py
from django.conf.urls import patterns, url urlpatterns = patterns(
'api.views',
url(r'^object/$', views.Object.as_view()),
) # views.py
from rest_framework.views import APIView
from rest_framework.response import Response
from django.views.decorators.csrf import csrf_exempt class 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 ?

asked Jun 16 '15 at 14:49
Irene Texas

211136
 
    
You are already using @csrf_exempt token. You can use this on the whole view. Shouldn't that work? – mukesh 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. – Irene Texas 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:stackoverflow.com/questions/34789301/… – The Brewmaster Jan 17 '16 at 10:13

6 Answers

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.

answered Jun 16 '15 at 18:50
Rahul Gupta

16.5k22332
 
    
Thanks, great answer. There should be a built in way to do this in restframework, but currently this is the best solution I found. – Omer Oct 13 '15 at 14:06
1  
Thank you, it worked! with Django 1.9 – neosergio 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? – Paolo 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. – Rahul Gupta Feb 6 at 6:09 

最新文章

  1. Spring--通过注解来配置bean【转】
  2. vim c++补全
  3. 线性表基本维护[ACM]
  4. WPF:xmal 静动态资源
  5. List<IPoint> to IPointCollection to IPolygon
  6. 1053: [HAOI2007]反素数ant - BZOJ
  7. Redis_基本类型介绍和指令___3
  8. AWS deepracer
  9. js的closures(闭包)
  10. c++数据类型漫谈
  11. LDAP2-创建OU创建用户
  12. keil安装
  13. 20155328 2016-2017-2 《Java程序设计》第7周学习总结
  14. 用vue实现登录页面
  15. echarts官网上的动态加载数据bug被我解决。咳咳/。
  16. 【278】◀▶ Python 数学函数说明
  17. 分词(Tokenization) - NLP学习(1)
  18. Kafka+SparkStreaming+Zookeeper(ZK存储Offset,解决checkpoint问题)
  19. 怎么快速对DB里的所有email进行校验
  20. 88E1111

热门文章

  1. 自做CA自签发SSL证书
  2. 4C 2018 福到了
  3. ansible 2.7.1 快速开始
  4. JAVA中的编码分析
  5. 10.1综合强化刷题 Day1
  6. 【Kafka】《Kafka权威指南》——分区partition
  7. Win7下搭建外网环境的SVN服务器
  8. CSS属性clip
  9. tomcat部署不成功 Deployment failure on Tomcat 6.x. Could not copy all resources to
  10. dubbo服务接口开发者必备调试利器,你值得拥有