-1

Iam doing an ajax call in Typescript which calls an internal Webservice. All endpoints whit "GET" are working, but whit "POST" it says

"403 Forbidden" - "detail: CSRF Failed: CSRF cookie not set"

Things i tried to fix the issue:

Nothing of this has worked, everytime still the same error occurs.

Here is my code in Typescript:

sendMessage(message, receiverId){
    let self = this;
    var message_obj = "{\"id\":\""+ GUID.generateGUID() +"\",\"message\":\""+ message +"\",\"receiverId\":\""+ receiverId + "\",\"moddate\":\""+ Date.now() +"\"}";
    var message_json = JSON.parse(message_obj);
    $.ajax({
        type: "POST",
        url: "/chat/message/",
        data:{"message_object":message_json},
        credentials: 'same-origin',
        success: function (response) {
            alert(response);
        },
        error: function (jqXHR, textStatus, errorThrown) {
            alert(errorThrown);
        }
    })
}

This is an example of an working ajax call:

getMessages(){
    let self = this;
    $.ajax({
        type: "GET",
        url: "/chat/message/",
        dataType: "json",
        success: function (response) {
            response = JSON.stringify(response);
            alert(response);
        },
        error: function(jqXHR, textStatus, errorThrown){
            alert(errorThrown);
        }
    })
}

EDIT:

Here is where i tryed to use csrf_exempt:

URLS.PY

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

from chat_api import views

urlpatterns = [
    url(r'^message/$', csrf_exempt(views.ChatMessageAPIEndpoint.as_view())),
    url(r'^message/(?P<commit>([0-9a-fA-F])+)', csrf_exempt(views.ChatMessageAPIEndpoint.as_view())),
    url(r'^devicekey/(?P<devid>([\w+-:])+)', views.DeviceAPIEndpoint.as_view()),
    url(r'^devicekey/$', views.DeviceAPIEndpoint.as_view()),
    url(r'^contacts/$', views.ContactAPIEndpoint.as_view()),
    url(r'^read/$', views.ReadStatusEndpoint.as_view()),
]

VIEWS.PY

    @csrf_exempt
    @need_post_parameters([PARAM_MESSAGE_OBJ])
    def post(self, request, *args, **kwargs):
        data = request.POST.get(PARAM_MESSAGE_OBJ)

        try:
            message_obj = json.loads(data)
        except Exception as e:
            return HttpResponseBadRequest(error_json("Could not parse JSON"))
...
Tim
  • 245
  • 3
  • 6
  • 18
  • Show how you attempted to use `@csrf_exempt`. [mcve] – Håken Lid Aug 30 '17 at 08:07
  • The django docs has an example of how to include the CSRF token in ajax requests using `jQuery.ajax()`. You have to include a `X-CSRFToken` header. https://docs.djangoproject.com/en/1.11/ref/csrf/#ajax – Håken Lid Aug 30 '17 at 08:09
  • @HåkenLid I tryed: csrf_exempt(views.ChatMessageAPIEndpoint.as_view()) and i tryed to set it as annotation in front of the Endpoint methods – Tim Aug 30 '17 at 08:22
  • Also i tryed the Django docs example but it also doestn work! I debugged the Django docs example but on the part: "if (document.cookie && document.cookie !== '') {" it goes out and returns null! – Tim Aug 30 '17 at 08:24
  • Include **in the question** the actual code where you did `csrf_exempt(views.ChatMessageAPIEndpoint.as_view())` https://docs.djangoproject.com/en/1.11/topics/class-based-views/intro/#decorating-class-based-views – Håken Lid Aug 30 '17 at 08:29
  • Your client side code has to **extract the token from a cookie** and **include the token in each ajax request**. The header should look something like this: `X-CSRFToken: i8XNjC4b8KVok4uw5RftR38Wgp2BFwql` – Håken Lid Aug 30 '17 at 08:37
  • @HåkenLid I only got a session cookie. As i said it fails at `if (document.cookie && document.cookie !=="" `. If i type document.cookie directly into the Browser console, it simpy returns ""! – Tim Aug 30 '17 at 08:41
  • Here's an question about how to use `csrf_exempt` with class based views. https://stackoverflow.com/questions/27315592/csrf-exempt-does-not-work-on-generic-view-based-class – Håken Lid Aug 30 '17 at 08:45
  • The cookie might be missing because you have disabled it somewhere. You can use the `ensure_csrf_cookie` decorator on the view where you need the cookie. https://docs.djangoproject.com/en/1.8/ref/csrf/#django.views.decorators.csrf.ensure_csrf_cookie – Håken Lid Aug 30 '17 at 08:50
  • You have to choose whether you want csrf protection or not. Disabling it some places and enabling it elsewhere will only lead to a mess. The default is to have the csrf cookie included everywhere. – Håken Lid Aug 30 '17 at 08:52
  • Ive tried it but it also doesnt work. I tryed to debug the Python script and it seems like it doesnt even comes there. Could it be, that the error is thrown on the Client side? In Typescript etc? – Tim Aug 30 '17 at 08:53
  • I want to enable it but all i try to make it working fails. – Tim Aug 30 '17 at 08:55

1 Answers1

0

I have found the mistake and i will post it here for equal errors:

My Classes in Views.py where using "Oauth2APIView"! Changing it into "View" did solve the problem for me!

Tim
  • 245
  • 3
  • 6
  • 18