Django’s CSRF protection may make it difficult to send an AJAX POST without getting a 403 Forbidden error. The following steps make it possible to send POST requests both with AJAX and/or SOAPUI.
Pre-requisite:
Somehwere in Django’s html template, include a:
1 |
{% csrf_token %} |
This will generate a hidden input field in the DOM called csrfmiddlewaretoken:
Making It Work With AJAX
Before using the actual $.ajax() function, include this $.ajaxSetup() prior to it:
1 2 3 4 5 |
$.ajaxSetup({ beforeSend: function(xhr, settings) { xhr.setRequestHeader("X-CSRFToken", $('input[name=csrfmiddlewaretoken]').val()); } }); |
This JQuery call
1 |
$('input[name=csrfmiddlewaretoken]').val() |
will take the value of the csrfmiddlewaretoken field generated in the DOM and add it as a header in the outgoing request. Seeing this token in the request will satisfy Django’s CSRF protection and let the request through.
Making It Work With SoapUI
Sending a POST request from SoapUI to Django requires adding the same X-CSRFToken header to the outgoing request. Additionally, a Cookie header called csrftoken needs to be added as well. The value of the cookie is likely to remain the same for an extended period of time, while the X-CSRFToken is generated fresh on every page load. However, used from SoapUI, both values can be reused for consecutive requests without any issues.
The value of the cookie is sent from Django on the first load of a page. In Developer Tools go to Network and click on the URI of the loaded page and copy it from the Response Headers. If the page was already reloaded multiple times then the value will be in the Request Headers instead:
The final SoapUI POST configuration includes both of the header fields: