iPhone POSTing to Django and gets CSRF verification failed

前端 未结 2 1767
青春惊慌失措
青春惊慌失措 2021-02-11 01:15

I send a POST request from IPhone to Django and get \"CSRF verification failed\", which I can\'t perfectly understand. I tried to find a good solution over the internet, but I c

相关标签:
2条回答
  • 2021-02-11 01:44

    Am I wrong or it just don't make sense to use this on native app?

    In that case, you could just disable this protection using this decorator:

    from django.views.decorators.csrf import csrf_exempt
    @csrf_exempt
      def view_without_csrf_protection(request):
        pass
    
    0 讨论(0)
  • 2021-02-11 01:50

    Normally this boils down to setting the headers correctly. There is an answer that already details this. The relevant part you need is this:

    xhr.setRequestHeader("X-CSRFToken", token)
    

    See the linked answer for details on getting the token from the cookies, for brevity I didn't copy it from there. I don't really know the context of your code, so this method of retrieval might not directly apply. Regardless, you need to get the token somehow.

    When you have the token, add a header to the NSMutableURLRequest. Upon posting the request, the error should be gone.

    [request addValue:token forHTTPHeaderField:@"X-CSRFToken"];
    
    0 讨论(0)
提交回复
热议问题