Laravel Sanctum middleware issue: CSRF token mismatch.

Updated: Jan 29, 2025

Laravel Sanctum middleware issue: CSRF token mismatch.

Laravel Sanctum is a simple, lightweight token-based authentication system for Laravel. It's designed to provide a stateless API authentication solution, making it an excellent choice for building modern, scalable applications. However, sometimes, developers may encounter a CSRF token mismatch issue when using Laravel Sanctum middleware. In this answer, we'll discuss the possible causes and solutions for this problem.

  1. CSRF token not sent with the request:

The most common cause of a CSRF token mismatch issue is not sending the CSRF token with the request. Laravel Sanctum relies on the CSRF token to validate the authenticity of incoming requests. To resolve this issue, ensure that you're sending the CSRF token with every request.

To send the CSRF token with the request, you need to include it in the headers or the body of the request. Laravel Sanctum uses the 'X-CSRF-TOKEN' header by default to send the token. So, you can either set this header in your client-side code or use Laravel's built-in CSRF protection middleware to add the token to the headers automatically.

Here's an example of how to set the CSRF token header in JavaScript:

axios.defaults.headers.common['X-CSRF-TOKEN'] = document.head.querySelector('meta[name="csrf-token"]').content;
  1. Incorrect CSRF token:

Another possible cause of a CSRF token mismatch issue is using an incorrect or stale CSRF token. Laravel generates a new CSRF token whenever a user logs in or visits a new page. So, if you're using an old token, you'll encounter a CSRF token mismatch error.

To resolve this issue, ensure that you're always using the latest CSRF token. You can get the latest CSRF token by making a request to the '/sanctum/csrf-cookie' endpoint or by reading the 'X-CSRF-TOKEN' header from the response of the last successful request.

  1. CSRF protection middleware not applied:

If you're not applying the Laravel Sanctum middleware to your routes, you'll encounter a CSRF token mismatch issue. The middleware is responsible for validating the CSRF token and protecting your routes from unauthorized access.

To apply the Laravel Sanctum middleware to your routes, add the following line to your route file:

Route::middleware(['sanctum:auth'])->group(function () {
    // Your protected routes go here
});
  1. Incorrect middleware configuration:

If you've applied the Laravel Sanctum middleware but still encountering a CSRF token mismatch issue, check your middleware configuration. Make sure that you've registered the Laravel Sanctum service provider and the 'Sanctum' middleware in your 'app/Providers/AppServiceProvider.php' file.

use Illuminate\Support\Facades\Gate;
use Laravel\Sanctum\Sanctum;

public function register()
{
    Gate::define('admin', function ($user) {
        return $user->role === 'admin';
    });

    if (!app()->environment('production')) {
        app()->register(Sanctum\SanctumServiceProvider::class);
        Sanctum::routes();
    }
}

Also, make sure that you've added the 'Sanctum' middleware to the 'web' middleware group in your 'app/Http/Kernel.php' file.

protected function routeMiddleware()
{
    return [
        'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'bindings' => \Illuminate\Routing\Middleware\SubscriptionBindingMiddleware::class,
        'session.start' => \Illuminate\Session\Middleware\StartSession::class,
        'csrf' => \Illuminate\Routing\Middleware\CSRF::class,
        'sanctum' => \Laravel\Sanctum\Http\Middleware\HandleSanctumState::class,
    ];
}

In conclusion, a CSRF token mismatch issue in Laravel Sanctum can be caused by various factors, including not sending the CSRF token with the request, using an incorrect or stale CSRF token, not applying the Laravel Sanctum middleware, or incorrect middleware configuration. By following the solutions provided in this answer, you should be able to resolve the CSRF token mismatch issue and secure your Laravel API application.