phplaravelvue.jslaravel-8laravel-sanctum

Vue + Laravel sanctum CSRF token mismatch 419 error


I get a "419 (unknown status)" error with the message "CSRF token mismatch."

POST http://127.0.0.1:8000/login 419 (unknown status)

CSRF token mismatch.

Laravel server : http://127.0.0.1:8000

Vue server : http://localhost:8080

app/Http/Kernel.php

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

app/Models/User.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;
    //...
}

config/cors.php

<?php

return [
    'paths' => [
        'api/*',
        'sanctum/csrf-cookie',
        'register',
        'login',
    ],
    'allowed_methods' => ['*'],
    'allowed_origins' => ['*'],
    'allowed_origins_patterns' => [],
    'allowed_headers' => ['*'],
    'exposed_headers' => [],
    'max_age' => 0,
    'supports_credentials' => true,
];

.env

SESSION_DRIVER=cookie
SESSION_DOMAIN=localhost
SANCTUM_STATEFUL_DOMAINS=localhost:8080

src/main.js

axios.interceptors.request.use((config) => {
    config.baseURL = 'http://127.0.0.1:8000'
    config.withCredentials = true

    return config
})

src/views/auth/Login.vue

import axios from 'axios'
import { reactive } from '@vue/reactivity';

export default {
    setup() {

        const credential = reactive({
            email: '',
            password: '',
        })

        const login = async () => {
            axios.get('/sanctum/csrf-cookie').then( async () => {
                let response = await axios.post('/login', credential)
                console.log(response);
            });
        }

        return { login, credential }
    }
};

Solution

  • You have your SANCTUM_STATEFUL_DOMAINS set to localhost:8080, but the rest of the code shows you're running on port 8000 instead of 8080. If you change that to 8000 you should be golden.