1

I'm using Vuejs and I want to make an secure AJAX request (with axios) to my laravel server, but I think that CSRF protections doesn't work because I change the token of the frontend part and even then I can interact with the database.

I read that Laravel come with a file named [bootstrap.js] (https://laravel.com/docs/5.8/csrf#csrf-introduction) it is assumed that this file does this task by default, but it doesn't work for me. I think it's beacuse webpack doens't load the file when I run npm run watch but I don't know how to load it,

I searched for an answer but I only find Bootstrap tutorials :/

2
  • you are using laravel 5.8? Commented May 31, 2019 at 1:30
  • No, im using Laravel Framework 5.6.39 Commented May 31, 2019 at 1:34

3 Answers 3

1

In head:

<meta name="csrf-token" content="{{ csrf_token() }}">

In ajax:

window.axios = require('axios');

window.axios.defaults.headers.common = {
    'X-CSRF-TOKEN' : document.querySelector('meta[name="csrf-token"]').getAttribute('content');
};

Sign up to request clarification or add additional context in comments.

Comments

0

You can put the CSRF in the meta as _token. Like this:

<meta name="csrf-token" content="{{ csrf_token() }}">

Visit the laravel documentation for this. https://laravel.com/docs/5.6/csrf#csrf-x-csrf-token

And then access it in your javascript.

Comments

0

You should add VerifyCsrfToken middleware for the API group (app/Http/Kernel.php)

2 Comments

Sounds logic let me see. But I need to include meta tag in my axios code ? Or it is automatic?
This declaration so your route will be wrapper middleware. So you need to include meta tag in the header of axios to passed

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.