Should Laravel SPA still use the CSRF token for security?

I ran into several difficulties with CSRF when creating a small SPA with Laravel and Vue.js:

  • I use index.html as the only view, the rest are processed by vue-router using separate file components (i.e. .vue files)
  • Since I do not use PHP or Blade on the front panel, I cannot insert csrf_token() into my view. Even if I did, the token would eventually expire, but due to the fact that the application does not have (or very few) page updates, it would not know if the token has changed, and ultimately it will not be able to make requests AJAX with an old token
  • Some answers suggest passing the token to a cookie and then retrieving it using JS. This approach suffers from the same problem as above - SPA is never notified when token changes
  • I could dig into Laravel's inner workings and throw an event every time the token changes; front-end can use Laravel Echo to listen for changes, but then the question is, is it even worth the worry?
  • Finally, I was offered to use JWT; however, as I understand it, JWT is used for authentication purposes, and CSRF is used for each individual request, regardless of the HTTP verb or intention.

Given the last two points, do you consider it necessary / advisable to use the CSRF token in the Laravel SPA club? And if so, what would be the best implementation (cookie with a token, a dedicated route returning a token, or another)? If not, what are the alternatives?

+5
source share
1 answer

Comments do not have enough space , so I add this as an answer, but this is just a concept, since I have very low experience with Vue.


From the documents

 // Add a request interceptor axios.interceptors.request.use(function (config) { // Do something before request is sent return config; }, function (error) { // Do something with request error return Promise.reject(error); }); // Add a response interceptor axios.interceptors.response.use(function (response) { // Do something with response data return response; }, function (error) { // Do something with response error return Promise.reject(error); }); 

So, the concept would be something like this:

  • Set a custom title from Laravel .
  • When creating / starting a Vue application, get your own header and set it somewhere global.
  • When executing the request, intercept it and add the CSRF token from global storage

    axios.interceptors.request.use (function (config) {// Get your token from where you saved it and add it to the request});

  • Intercept the answer and save the new token

    axios.interceptors.response.use (function (response) {// Store the new CSRF token in the same place where you saved the first.});

  • Loop forever

+3
source

Source: https://habr.com/ru/post/1268307/


All Articles