Django REST Framework CSRF 失败:CSRF cookie 未设置 [英] Django REST Framework CSRF Failed: CSRF cookie not set
问题描述
我正在使用 django rest 框架通过 IOS 执行 API 调用我收到以下错误CSRF 失败:CSRF cookie 未设置."
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
....
我能做什么?
推荐答案
如果有人还在关注这个问题,直接的答案是你需要在视图方法本身上使用装饰器.在 APIView
类上定义的 get
和 post
方法只是告诉 DRF 实际视图应该如何表现,但是 django 路由器期望的视图方法在您调用 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 cookie 未设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!