Django REST Framework CSRF失败:未设置CSRF Coo​​kie [英] Django REST Framework CSRF Failed: CSRF cookie not set

查看:39
本文介绍了Django REST Framework CSRF失败:未设置CSRF Coo​​kie的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用django rest框架通过IOS执行API调用我得到以下错误"CSRF失败:未设置CSRF Coo​​kie."

I am using the django rest framework to perform API calls via IOS and I get the following error "CSRF Failed: CSRF cookie not set."

这是我的django API代码:

Here's my django API code:

class LoginView(APIView):
    """
    List all snippets, or create a new snippet.
    """
    @csrf_exempt
    def get(self, request, format=None):
        startups = Startup.objects.all()
        serializer = StartupSerializer(startups, many=True)
        return Response(serializer.data)

    @csrf_exempt
    def post(self, request, format=None):
        profile = request.POST
....

我该怎么办?

推荐答案

如果仍然有人在关注这个问题,直接的答案是您需要在view方法本身上使用装饰器.在 APIView 类上定义的 get post 方法只是告诉DRF实际视图的行为,但是django路由器期望的view方法直到您调用 LoginView.as_view()时才真正实例化.

If anyone is still following this question, the direct answer is that you need to use the decorator on the view method itself. The get and post methods defined on the APIView class just tell DRF how the actual view should behave, but the view method that the django router expects is not actually instantiated until you call LoginView.as_view().

因此,解决方案是将 csrf_exempt 装饰器添加到 urls.py .它可能如下所示:

Thus, the solution is to add the csrf_exempt decorator to urls.py. It might look as follows:

#file: urls.py

from django.conf.urls import patterns, url
from django.views.decorators.csrf import csrf_exempt

import views

urlpatterns = patterns('',
    url('^login/$', csrf_exempt(views.LoginView.as_view())),
    ...
)

但是,正如Mark所指出的,csrf保护对于防止会话被劫持非常重要.我自己尚未使用iOS,但我会考虑使用django的基于cookie的csrf令牌.您可以使用 ensure_csrf_cookie 装饰器使django发送带有响应的 csrftoken cookie,并且只要包含以下内容,您的 POST 请求就会生效令牌作为 X-CSRFToken 标头.

However, as Mark points out above, csrf protection is important to prevent your sessions from being hijacked. I haven't worked with iOS myself, but I would look into using django's cookie-based csrf tokens. You can use the ensure_csrf_cookie decorator to make django send a csrftoken cookie with a response, and your POST requests will validate as long as you include that token as an X-CSRFToken header.

这篇关于Django REST Framework CSRF失败:未设置CSRF Coo​​kie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆