I ran into multiple difficulties with CSRF when building a small SPA with Laravel and Vue.js:
index.html
as the only view, the rest is handled by vue-router
using single file components (i.e. .vue
files)csrf_token()
into my view. Even if I did, the token would eventually expire, yet because the app has no (or very few) page refresh(es), it wouldn't know if the token changed, and it would eventually fail to make AJAX requests with the old tokenWith the last two points in mind, do you think it is necessary/advisable to use a CSRF token in a Laravel SPA? And if so, what would be the best implementation (cookie with the token, dedicated route returning the token, or other)? If not, what are the alternatives?
Laravel CSRF Token Ajax Calls In Laravel, Middleware handles all the requests and doesn't allow any POST request without the right CSRF token verification. Therefore, in order to proceed further, you must input the CSRF Token while sending the AJAX request.
Such carefully executed Social Engineering is not always needed to perform CSRF attacks, however. In fact, every single webpage you visit can perform CSRF; surfing the Web requires a lot of trust.
Laravel automatically generates a CSRF "token" for each active user session managed by the application. This token is used to verify that the authenticated user is the person actually making the requests to the application.
Changing the CSRF token on every request provides adequate protection against BREACH, and both Django and Rails have implemented changing CSRF tokens. Both frameworks have implemented it by encoding the actual CSRF token. The token is encoded randomly on each page, thus preventing repetitive output.
Comments don't have enough space, so I'm adding this as an answer, but this is just a concept as I have extremely low experience with Vue.
From the docs
// 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:
When making a request, intercept it and add the CSRF token from the global storage
axios.interceptors.request.use(function (config) { // Get your token from the place you stored it and add to the request });
Intercept the response and store a new token
axios.interceptors.response.use(function (response) { // Store the new CSRF token in the same place you stored the 1st one. });
Loop forever
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With