Laravel CSRF Token Mismatch Error Message

One in a lifetime, Laravel developers face CSRF token mismatch error message in the Laravel. CSRF token is very useful to protect the HTTP requests.

Throughout this article, we will learn about how to solve CSRF token mismatch error, change the error message in a user-readable form, how to exclude your special route from the CSRF protection, etc.

Let’s start this article with a bang!

Table of Contents
1. Why CSRF Token Mismatch Error Occurs
2. Solution 01: Simple Form Submission
3. Solution 02: AJAX Based Requests
4. Exclude URIs From CSRF Protection
5. Change CSRF Token Mismatch Error Message In Laravel

Why CSRF Token Mismatch Error Occurs

As per our real-life experience we found that this error occurs due to the following reasons:

  1. You might forget to include a hidden CSRF (cross-site request forgery) token field in the form.
  2. If you are submitting an AJAX-based request using jQueryJavaScriptVue, etc then you might forget to include X-CSRF-TOKEN request header.
  3. Your session might be expired and without refreshing a page, you are submitting a form or request.

These are the basic reasons for CSRF mismatch error occurs. Now, let’s see how to resolve the error.

Solution 01: Simple Form Submission

If you have the simple form and if you are not using any other mechanism to submit a form then you just need to include a hidden CSRF _token field in the form so that the CSRF protection middleware can validate the request.

To do that you can use @csrf blade directive that will generate hidden field automatically for you or you can write hidden field as below:

1
2
3
4
5
@csrf
 
// Or
<!-- Equivalent to... -->
<input type="hidden" name="_token" value="{{ csrf_token() }}" />

Both @csrf and <input type="hidden" ...> are equal as shown in the above code.

Solution 02: AJAX Based Requests

For the AJAX-based requests, you need to add the following meta tag in <head></head>

1
<meta name="csrf-token" content="{{ csrf_token() }}"> // Add in <head></head>

After that, include the following code before you request call

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

You don’t need to repeat the above code for each request. But you need to include the above code on each page where the request is being fired of.

Exclude URIs From CSRF Protection

Sometimes you may wish to exclude the URLs from the CSRF protection. For example, if you are using any 3rd party services and in that you might need to submit a form from your website in that case, you don’t need to use CSRF token.

If you don’t exclude that specific URL then Laravel show you the error message. So to exclude URI follow the steps as below:

  1. Go to the app/Http/Middleware directory and open the VerifyCsrfToken.php file.
  2. Now, in protected $except array, add your URIs like below and you are done.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<?php
 
namespace App\Http\Middleware;
 
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as Middleware;
 
class VerifyCsrfToken extends Middleware
{
    /**
     * The URIs that should be excluded from CSRF verification.
     *
     * @var array
     */
    protected $except = [
        'stripe/*',
        'http://example.com/foo/bar',
        'http://example.com/foo/*',
    ];
}

Change CSRF Token Mismatch Error Message In Laravel

Recently, we were working on a Laravel + Vue based project. In that, we have added auto logout functionality if a user is inactive for more than 15 mins. But after the logout session is expired and due to that if the user re-try to login they were getting the “CSRF token mismatch” error so they have reported this issue to the site admin.

So due to that site admin wants to change that message in user-readable form like “Your session has expired. You will need to refresh the page and log in again to continue using the system.” This message is meaningful to users and they won’t see the error message again after refreshing the page. Let’s see how to change the CSRF Token Mismatch error message.

  1. First, go to the app/Exceptions directory and open the Handler.php file.
  2. In render() method add the following code.
1
2
3
4
5
6
7
8
if ($request->expectsJson()) {
 
    if ($exception instanceof TokenMismatchException) {
        return response()->json([
        'message' => 'Your session has expired. You will need to refresh the page and login again to continue using the system.'], 419);
    }
 
}

That’s it. You are done.

If you want to test the newly added message then open your site and open the developer tools by inspect element option.

Then, Delete the XSRF-TOKEN cookie and then try to submit your form or request again. You will see the newly added message.

Remove XSRF Token Using Browser's Developer ToolRemove XSRF Token Using Browser’s Developer Tool

Additionally, read our guide:

  1. Laravel One To One Relationship Tutorial
  2. Best Way to Remove Public from URL in Laravel
  3. How To Print Or Debug Query In Laravel
  4. Specified Key Was Too Long Error In Laravel
  5. AJAX PHP Post Request With Example
  6. How To Use The Laravel Soft Delete
  7. How To Add Laravel Next Prev Pagination
  8. Laravel Remove Package With Example (Correct Way)
  9. Difference Between Factory And Seeders In Laravel
  10. Laravel: Increase Quantity If Product Already Exists In Cart
  11. How To Calculate Age From Birthdate
  12. How to Convert Base64 to Image in PHP
  13. Check If A String Contains A Specific Word In PHP
  14. How To Find Duplicate Records in Database
  15. How To Convert Word To PDF In Laravel

That’s it for now. We hope this article helped you to learn Laravel CSRF Token Mismatch Error Message related things.

Please let us know in the comments if everything worked as expected, your issues, or any questions. If you think this article saved your time & money, please do comment, share, like & subscribe. Thank you in advance. 🙂 Keep Smiling! Happy Coding!

posted on 2022-04-06 10:03  刘应杰  阅读(747)  评论(0编辑  收藏  举报

导航