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 

Django Rest Framework remove csrf的更多相关文章

  1. django rest framework csrf failed csrf token missing or incorrect

    django rest framework csrf failed csrf token missing or incorrect REST_FRAMEWORK = { 'DEFAULT_AUTHEN ...

  2. 用Django Rest Framework和AngularJS开始你的项目

    Reference: http://blog.csdn.net/seele52/article/details/14105445 译序:虽然本文号称是"hello world式的教程&quo ...

  3. Getting Started with Django Rest Framework and AngularJS

    转载自:http://blog.kevinastone.com/getting-started-with-django-rest-framework-and-angularjs.html A ReST ...

  4. django rest framework 入门

    django rest framework 入门1-序列化 Serialization 分类: Python 2013-01-22 22:24 11528人阅读 评论(0) 收藏 举报 djangop ...

  5. Django REST Framework学习——Android使用REST方法访问Diango

    本文更应该叫做Android如何模拟浏览器访问Django服务器后台. 环境为: Android通过HttpClient访问服务器,从Django中获取json数据,解析显示在UI界面上. 问题为: ...

  6. Django REST framework 中文教程1:序列化

    建立环境 在我们做任何事情之前,我们将使用virtualenv创建一个新的虚拟环境.这将确保我们的包配置与我们正在开展的任何其他项目保持良好的隔离. virtualenv envsource env/ ...

  7. Django REST framework+Vue 打造生鲜超市(五)

    六.商品类别数据展示 6.1. 商品类别数据接口 (1)商品分类有两个接口: 一种是全部分类:一级二级三级 一种是某一类的分类以及商品详细信息: 开始写商品分类的接口 (2)序列化 给分类添加三级分类 ...

  8. Python Django rest framework

    本节内容 Django rest framework 安装 Django rest framwwork 环境配置 简单举例说明 Django中使用 rest framework 1.1 安装 Djan ...

  9. Django REST Framework API Guide 06

    本节大纲 1.Validators 2.Authentication Validators 在REST框架中处理验证的大多数时间,您将仅仅依赖于缺省字段验证,或在序列化器或字段类上编写显式验证方法.但 ...

随机推荐

  1. C# Stopwatch详解

    namespace System.Diagnostics { // // 摘要: // 提供一组方法和属性,可用于准确地测量运行时间. public class Stopwatch { // // 摘 ...

  2. 搜狗拼音输入法LINUX版安装

    搜狗拼音输入法LINUX版官方下载: http://pinyin.sogou.com/linux/?r=pinyin 一.添加fcitx的nightlyPPA 在终端中输入: sudo add-apt ...

  3. Codeforces Gym100971 C.Triangles-组三角形 (IX Samara Regional Intercollegiate Programming Contest Russia, Samara, March 13)

    这个题就是组三角形,从给出的数组里任选两个和未知的边组三角形. 任意两边之和大于第三边,记住这个就可以了. 代码: 1 #include<cstdio> 2 #include<cst ...

  4. 记一次kubernetes集群异常: kubelet连接apiserver超时

    Background kubernetes是master-slave结构,master node是集群的大脑, 当master node发生故障时整个集群都"out of control&q ...

  5. Android学习--持久化(一) 文件存储

    持久化之   文件存储 这里把Android持久化全都整理一下,这一篇文章先简单的说一下文件的存储,通过下面一个简单的Demo,理解一下这个文件存储,先说说下面Demo的思路: 1.创建EditTex ...

  6. FactoryMethod

    工厂方法模式 定义:定义一个用于创建对象的接口,让子类决定实例化哪一个类,工厂方法使一个类的实例化延迟到其子类 工厂方法的简单实现 (1)创建简单的产品接口 /** * 创建产品接口 * @autho ...

  7. 标签页的切换方法(DOM)

    效果: 1.点击“JAVA语言” 2.点击“C语言” 3.点击C++语言 代码: <!doctype html> <html> <head> <meta ch ...

  8. ArcObject开发,“异常在 ESRI.ArcGIS.Version.dll”错误

    “System.DllNotFoundException”类型的未经处理的异常在 ESRI.ArcGIS.Version.dll 中发生 其他信息: 无法加载 DLL“ArcGISVersion.dl ...

  9. dedecms图片列表效果调用

    效果如图 代码如下: <div class="listbox"> <ul class="e1"> {dede:list pagesize ...

  10. 【重点突破】——使用Canvas进行绘图图像

    一.引言 本文主要是canvas绘图中绘制图像的部分,做了几个练习,综合起来,复习canvas绘图以及定时器的使用. 二.canvas绘制小飞机在指定位置 <!DOCTYPE html> ...