0

I'm trying to send a POST request from a Vue.js template to my API created with Django. When sending I get a 403 CSRF token missing or incorrect error. Since I separated the front and the back, I don't have a view with {csrf_token} on the Django side.

How do I send my form?

I tried some exemples on the web using cookies but i'm beginners and need more explaination about the POST subject and CSRF

I have a Djano View (and urls associated) juste like this :

def get_csrf_token(request):
token = get_token(request)
return JsonResponse({'token': token})

Whe i'm requesting the url, obtained the JSON with the token.

And on the Front side i'm using this method to get the Token :

getToken: function() {
                this.loading = true;
                this.$http.get('/qualite/get-token/')
                    .then((response) => {
                        this.token =response.data;
                        this.loading = false;
                    })
                    .catch((err) => {
                        this.loading = false;
                        console.log(err);
                    })
            },


addNc: function() {
                    let headers = {
                        'Content-Type': 'application/json;charset=utf-8'
                    };
                    if(this.token !== '') {
                        headers['HTTP_X-XSRF-TOKEN'] = this.token
                    }

                    this.loading = true;
                    this.$http.post('/qualite/api/nc/',this.newNc, {headers: headers})
                        .then((response) => {
                            this.loading = false;
                        })
                        .catch((err) => {
                            this.loading = false;
                            console.log(err)
                        })
                },
QuRo
  • 59
  • 1
  • 6

3 Answers3

0

For the CSRF you get by default after user login aside with the session, if you're using SessionAuthentication (It's the default authentication used in DRF).

You have to send it with each request in the header, you can refer the this link to know more about the header sent, as it's name is changed and can be configured.

Note also that in the settings you have to make sure that CSRF_COOKIE_HTTPONLY is set to False (which is the default), to be able to read it from the client side JS.

Another path would be removing CSRF enforcement per requests (But it's highly not recommended for security concerns), you can find more about this in the answer here.

P. Naoum
  • 457
  • 5
  • 14
0

Use a Token-based authentification.

0

Same issue i was encountered with,

the problem was, i had used Class based view and at the time of registered the url i forget to mention as_view() with class Name.

ex:- class PostData(APIView)

before :- path('post_data', PostData)

after correction:- path('post_data', PostData.as_view())
C. Peck
  • 3,641
  • 3
  • 19
  • 36