Alzaabi98's avatar

Laravel Sanctum error CSRF token mismatchs

I am trying to play with laravel sanctum and configure as SPA but I am not able to get it working unless I disable the csrf protection in laravel app.

When I send the localhost/sanctum/csrf-cookie from postman , I can see the 204 response and cookies are displayed

I made simple vue app and install axios then I run simple login code like this one :

<script>
import axios from "axios";
axios.defaults.withCredentials = true;
axios.defaults.baseURL = "http://127.0.0.1:8000";
export default {
  methods: {
    login() {
      axios.get("/sanctum/csrf-cookie").then(response => {
        console.log(response); //This is one success but it did set cookie in application cookie
        axios
          .post("/login", {
            email: "[email protected]",
            password: "123456"
          })
          .then(res => {
            console.log(res);
          }); // this one failed with 419 csrf token mismatch
      });
    }
  }
};
</script>

also here is my backend cors

'paths' => ['api/*', 'sanctum/csrf-cookie', 'login', 'logout'],

    'allowed_methods' => ['*'],

    'allowed_origins' => ['*'],

    'allowed_origins_patterns' => [],

    'allowed_headers' => ['*'],

    'exposed_headers' => [],

    'max_age' => 0,

    'supports_credentials' => true,

];

here is api in routes :

Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
    return $request->user();
});

here is sanctum.php in config folder

    'stateful' => explode(',', env('SANCTUM_STATEFUL_DOMAINS', 'localhost,127.0.0.1')),

here is the sessions.config .. domain part

    'domain' => env('SESSION_DOMAIN', null),

I hope someone can help and let me what is wrong in my config ..

0 likes
10 replies
Holyflames's avatar
Level 1

If u are trying it on localhost, so u can try this one: (.env) settings: SESSION_DOMAIN=localhost SANCTUM_STATEFUL_DOMAINS=localhost It's helped for me.

20 likes
chaernh's avatar

@Holyflames How about if domain is live? Like the API domain is 'api.domain.com' and the client is 'domain.com' ? Is it like this?

SANCTUM_STATEFUL_DOMAINS=domain
SESSION_DOMAIN=api.domain
aisak's avatar

Me too have this problem, I have this error, in my file .env I add this: SESSION_DOMAIN=localhost SANCTUM_STATEFUL_DOMAINS=localhost

file sanctum.php

 'stateful' => explode(',', env(
        'SANCTUM_STATEFUL_DOMAINS',
        'localhost,localhost:8080,127.0.0.1,127.0.0.1:8080,::1'
    )),

config/cors.php

<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Cross-Origin Resource Sharing (CORS) Configuration
    |--------------------------------------------------------------------------
    |
    | Here you may configure your settings for cross-origin resource sharing
    | or "CORS". This determines what cross-origin operations may execute
    | in web browsers. You are free to adjust these settings as needed.
    |
    | To learn more: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
    |
    */

    'paths' => [
        'api/*', 
        '/*',
        'sanctum/csrf-cookie', 
        'register'
    ],

    'allowed_methods' => ['*'],

    'allowed_origins' => ['http://localhost:8080'],

    'allowed_origins_patterns' => [],

    'allowed_headers' => ['*'],

    'exposed_headers' => [],

    'max_age' => 0,

    'supports_credentials' => true,

];

Kernel.php

   protected $middleware = [
        \Fruitcake\Cors\HandleCors::class,
        \App\Http\Middleware\TrustHosts::class,
        \App\Http\Middleware\TrustProxies::class,
        \App\Http\Middleware\PreventRequestsDuringMaintenance::class,
        \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
        \App\Http\Middleware\TrimStrings::class,
        \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
   
    ];
 protected $middlewareGroups = [

        'api' => [
            EnsureFrontendRequestsAreStateful::class,
            'throttle:api',
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],
    ];


Route web.php

Route::post('register', [App\Http\Controllers\Auth\RegisterController::class, 'create']);
1 like
aisak's avatar

and vuejs i have this configuration in the file main.js

Vue.config.productionTip = false
Vue.prototype.$http = axios
axios.defaults.withCredentials = true
axios.defaults.baseURL = 'http://localhost:8000'

and my browser i have this response

Access to XMLHttpRequest at 'http://localhost:8000/register' from origin 'http://localhost:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

xhr.js?b50d:177 
POST http://localhost:8000/register net::ERR_FAILED
dispatchXhrRequest @ xhr.js?b50d:177
xhrAdapter @ xhr.js?b50d:13
dispatchRequest @ dispatchRequest.js?5270:52
Promise.then (async)
request @ Axios.js?0a06:61
Axios.<computed> @ Axios.js?0a06:87
wrap @ bind.js?1d2b:9
eval @ Register.vue?0103:90
Promise.then (async)
sendRegister @ Register.vue?0103:89
submit @ Register.vue?6581:15
invokeWithErrorHandling @ vue.runtime.esm.js?2b0e:1854
invoker @ vue.runtime.esm.js?2b0e:2179
invokeWithErrorHandling @ vue.runtime.esm.js?2b0e:1854
Vue.$emit @ vue.runtime.esm.js?2b0e:3888
submit @ VForm.ts?24e7:140
invokeWithErrorHandling @ vue.runtime.esm.js?2b0e:1854
invoker @ vue.runtime.esm.js?2b0e:2179
original._wrapper @ vue.runtime.esm.js?2b0e:6917
createError.js?2d83:16 Uncaught (in promise) Error: Network Error
    at createError (createError.js?2d83:16)
    at XMLHttpRequest.handleError (xhr.js?b50d:84)
kachi_dk's avatar

This worked for me. After adding this to the .env

SESSION_DOMAIN=http://localhost:XXXX
SANCTUM_STATEFUL_DOMAINS=http://localhost:XXXX

I ran this

php artisan config:cache

Please or to participate in this conversation.