Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

csrf_token of Django into Vuejs when seperate them

Tags:

django

vue.js

I am using ajax request to send POST but it got response 403 because of csrf_token. I divide the frontend just using Vuejs and backend using Django to just reponse API only so I can't use Django template to render {% csrf_token %} or having csrftoken in session to use getcookie('csrftoken') like in Django's doc recommend. Is there anybody face this problem like me and got some solutions ? So thank you if you can help me this.

like image 455
John T Avatar asked Apr 23 '17 03:04

John T


People also ask

What is Csrf how it's preventing in Django?

csrf_token. Django has a {% csrf_token %} tag that is implemented to avoid malicious attacks. It generates a token on the server-side when rendering the page and makes sure to cross-check this token for any requests coming back in. If the incoming requests do not contain the token, they are not executed.

How is CSRF token generated in Django?

How Does the CSRF Token Work? The CSRF token is like an alphanumeric code or random secret value that's peculiar to that particular site. Hence, no other site has the same code. In Django, the token is set by CsrfViewMiddleware in the settings.py file.


1 Answers

You can set the CSRF token in the header of your AJAX request. E.g., if you use jquery and jquery.cookie library, you can easily retrieve the Django-set csrftoken cookie like so:

$.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 includes 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 details everything pretty clearly.

EDIT:

Given that even your initial page request is not served by Django, here is 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.) You would also need to add an appropriate entry in your Django URLs file:

url(r'^get-token/$', get_csrf_token)

3.) Then your Vue.js app can fetch the CSRF token using this endpoint. This doesn't need to be a user-initiated event; for example, you can configure your front-end app to fetch it on the $(document).ready() event. Then, using your preferred AJAX library (I am 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.) Now your csrftoken cookie is set and should be usable 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 have used jQuery for AJAX functionality and the jQuery.cookie library for getting and setting cookies, but of course you can use whichever library you would prefer for these functions.

like image 167
nb1987 Avatar answered Sep 19 '22 09:09

nb1987