top of page
Writer's pictureThe Tech Platform

How to Fix Laravel CSRF Token Mismatch Error From AJAX Request

Updated: Mar 14, 2023

CSRF is an attack that forces an end user to execute unwanted actions on a web application where they are currently authenticated. Laravel's CSRF protection works by adding a CSRF token to all form submissions, which ensures that the request comes from an authenticated user and prevents malicious attacks. In this article, we will discuss how to fix the Laravel CSRF token mismatch error from AJAX requests.




What is CSRF Token Mismatch Error?

Cross-Site Request Forgery (CSRF) is a type of web attack that forces an authenticated user to perform unwanted actions on a web application. In a CSRF attack, the attacker tricks the victim into performing an action that they did not intend to perform, such as transferring money or changing their account password.


To prevent CSRF attacks, Laravel uses a built-in mechanism called CSRF protection. CSRF protection adds a unique token to every form submitted to the application. The token is checked on the server-side to ensure that the form submission comes from a legitimate source, i.e., the form is submitted by the authenticated user and not by an attacker.


The CSRF token mismatch error occurs when the token value in the request does not match the token value stored in the user's session. This error indicates that the request has been tampered with or that the token has expired.


Steps to Fix CSRF Token Mismatch Error from AJAX Request

When making AJAX requests to a Laravel application, you may encounter a CSRF token mismatch error. This error occurs because the CSRF token is not sent with the AJAX request, and Laravel is expecting it to be present. Follow the below steps to fix them:


Step 1: Add CSRF Token to AJAX Request Headers

To fix the CSRF token mismatch error, we need to add the CSRF token to the headers of our AJAX request. Laravel provides a convenient way to obtain the CSRF token using the csrf_token() function. This function returns the current CSRF token value, which we can use to add the CSRF token to the headers of our AJAX request.


Here's an example code snippet that demonstrates how to add the CSRF token to the headers of an AJAX request using jQuery:

$.ajaxSetup({
    headers: 
    {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});

In the above code snippet, we use the ajaxSetup() function provided by jQuery to set the headers for all AJAX requests. The X-CSRF-TOKEN header is set to the value of the CSRF token, which is obtained from the meta tag in the HTML document using the attr() function.


Step 2: Verify CSRF Token in Laravel Controller

After adding the CSRF token to the headers of our AJAX request, we need to verify the token in our Laravel controller. Laravel provides a middleware called VerifyCsrfToken that handles the CSRF token verification for all incoming requests, including AJAX requests.


However, when making AJAX requests to a Laravel application, we need to ensure that the X-CSRF-TOKEN header matches the CSRF token value stored in the user's session. To do this, we can add the web middleware group to our AJAX route in the routes/web.php file, which enables CSRF protection for AJAX requests.


Here's an example code snippet that demonstrates how to enable CSRF protection for an AJAX route:

Route::group(['middleware' => ['web']], function () 
{
    Route::post('/example', 'ExampleController@store');
});

In the above code snippet, we wrap our AJAX route in a web middleware group, which enables CSRF protection for AJAX requests. Now, when an AJAX request is made to the /example route, Laravel will verify that the X-CSRF-TOKEN header matches the CSRF token value stored in the user's session.


Step 3: Refresh CSRF Token on Session Timeout

In some cases, the CSRF token may expire before the user completes the form submission. This can happen if the user takes a long time to fill out the form, and their session times out. To prevent this issue, we can refresh the CSRF token on session timeout using JavaScript.


Here's an example code snippet that demonstrates how to refresh the CSRF token using JavaScript:

setInterval(function() 
{
    $.get('/refresh-csrf').done(function(data) 
    {
        $('meta[name="csrf-token"]').attr('content', data);
    });
}, 1800000); // 30 minutes

In the above code snippet, we use the setInterval() function to refresh the CSRF token every 30 minutes. We make an AJAX request to the `/refresh-csrf endpoint, which returns a new CSRF token value, and update the meta tag in the HTML document with the new token value.

Step 4: Display CSRF Token in View

Finally, to ensure that the CSRF token is available in all views, we need to include the token value in the HTML document. Laravel provides a convenient way to do this using the csrf_token() function. Here's an example code snippet that demonstrates how to include the CSRF token value in a hidden form field:

<form method="POST" action="/example">     
    @csrf     
    <input type="text" name="name">
    <button type="submit">Submit</button>
</form>

In the above code snippet, we use the @csrf directive provided by Laravel to include the CSRF token value in a hidden form field. This ensures that the token is submitted with the form data and verified in the Laravel controller.

Conclusion

We discussed how to fix the Laravel CSRF token mismatch error from AJAX requests. We learned how to add the CSRF token to the headers of our AJAX request, verify the token in our Laravel controller, refresh the CSRF token on session timeout, and display the CSRF token in the view. By following these steps, you can ensure that your Laravel application is secure from CSRF attacks and that your AJAX requests are properly authenticated.

0 comments

Comentários


bottom of page