#11 Part-2: Initialize Csrf Cookie in Vuejs and Laravel Application
When working with Vuejs and Laravel applications, it is essential to have proper csrf protection to prevent cross-site request forgery attacks. In this article, we will discuss how to initialize the csrf cookie in a Vuejs and Laravel application.
Step 1: Configure Laravel to Send Csrf Cookie
First, we need to configure our Laravel application to send the csrf token cookie with every response. This can be done by adding the following code in the `AppHttpMiddlewareVerifyCsrfToken` middleware:
protected $addHttpCookie = true;
Step 2: Initialize Csrf Cookie in Vuejs
Next, we need to initialize the csrf cookie in our Vuejs frontend. This can be done by making an API request to the Laravel backend to retrieve the csrf token and set it in the Vuejs application. Here is an example of how this can be done:
axios.get('/csrf-cookie') .then(response => { Vue.prototype.$csrfCookie = response.data.csrfToken; });
Step 3: Use Csrf Cookie in Axios Requests
Once the csrf token is set in the Vuejs application, we can use it in all Axios requests to the Laravel backend. We can set the csrf token as a header in the Axios instance to ensure that it is sent with every request. Here is an example of how this can be done:
axios.defaults.headers.common['X-CSRF-TOKEN'] = Vue.prototype.$csrfCookie;
Conclusion
By following the steps outlined in this article, you can initialize the csrf cookie in your Vuejs and Laravel application to help protect against cross-site request forgery attacks. It is important to ensure that proper csrf protection is in place to secure your application.
Good tutorial.I am getting 419 error while tryign to register.I tried to use the code from git too .Is there anything you missed out?