Csrf_token from Django to Vuejs when shared
I am using an ajax request to send a POST, but I got a 403 response because of the csrf_token. I split the frontend using Vuejs and the backend using Django to just respond to the API, so I can't use the Django template to render {% csrf_token%} or have a csrftoken in session to use getcookie ('csrftoken') like in the Django recommendation doc. Does anyone run into a problem like me and got some solutions? So thanks if you can help me.
source to share
You can set the CSRF token in the header of your AJAX request. For example, if you are using jquery library and jquery.cookie, you can easily get the Django-set cookie csrftoken
like this:
$.ajax({
url : 'YOUR_URL_HERE',
headers: {'X-CSRFToken': $.cookie('csrftoken')},
type: 'POST',
dataType: 'json',
data: {},
success: function() {
},
error: function(xhr, errMsg, err) {
},
});
Django documentation also has a section on this: https://docs.djangoproject.com/en/1.11/ref/csrf/#ajax
Please note that this solution may depend on your specific Django settings. The Django documentation link above explains everything in detail.
EDIT:
Considering that even your initial page request isn't being served by Django, here's how you can accomplish what you're looking for ...
1.) Create a view in your Django app that manually generates and returns a CSRF token (using django.middleware.csrf.get_token
):
def get_csrf_token(request):
token = django.middleware.csrf.get_token(request)
return JsonResponse({'token': token})
2.) Also you need to add the appropriate entry to your Django urls file:
url(r'^get-token/$', get_csrf_token)
3.) Then your Vue.js app can retrieve the CSRF token using this endpoint. This does not have to be a user-initiated event; for example, you can configure an external application to receive it in an event $(document).ready()
. Then, using your preferred AJAX library (I'm using jQuery in my example):
$.ajax({
url: '/get-token/',
type: 'GET',
dataType: 'json',
success: function(data) {
$.cookie('csrftoken', data.token); // set the csrftoken cookie
}
});
4.) Your cookie is now csrftoken
set and should be used for subsequent POST requests.
$.ajax({
url : 'YOUR_URL_HERE',
headers: {'X-CSRFToken': $.cookie('csrftoken')},
type: 'POST',
dataType: 'json',
data: {},
success: function() {
},
error: function(xhr, errMsg, err) {
},
});
I used jQuery AJAX function and jQuery.cookie library to get and set cookies, but of course you can use any library you prefer for these functions.
source to share
According to the Django documentation, you can just use a decorator ensure_csrf_cookie
on the view and send a cookie with a token using the response.
source to share