2

I'm using laravel 5.6 with axios and vue for my SPA web app. the problem is after a while the csrf token will expire so there should be an annoying prompt telling the user to refresh the page which is not what I'm looking for. so all I know about csrf token in laravel 5.6 is it's used in bootstrap.js in this way:

let token = document.head.querySelector('meta[name="csrf-token"]');

if (token) {
   window.axios.defaults.headers.common['X-CSRF-TOKEN'] = token.content;
} else {
  console.error('CSRF token not found: https://laravel.com/docs/csrf#csrf-x- 
  csrf-token');
}

how I change this to get the csrf token on each request?

  • The accepted answer to this question seems to be a decent implementation you could adopt to solve your problem: https://stackoverflow.com/questions/31449434/handling-expired-token-in-laravel – matpb Aug 15 '18 at 08:05

1 Answers1

3

create an endpoint for retrieving the latest csrf token:

ExampleController.php

public function getCsrf() {
  return response(csrf_token());
}

Route: (routes/wew.php)

Route::get('csrf', 'ExampleController@getCsrf');

In your Javascript, you can request for a new csrf token and replace the old one in your axios instance.

axios.get('/csrf').then(({ data }) => {
  window.axios.defaults.headers.common['X-CSRF-TOKEN'] = data;
})
Julian Paolo Dayag
  • 3,562
  • 3
  • 20
  • 32
  • will that make the application less secured? The purpose of the CSRF is the generate a secret token by not exposing that to outside world, but via this API endpoint, the purpose becomes void! So something like an easy cake for an attacker isn't it? – Harry Dec 10 '21 at 15:47