CSRF token mismatch error while authenticating Vue3 SPA with Laravel Fortify using axios

423 views Asked by At

I am trying to setup an SPA in Vuejs with Laravel 10 on localhost. I am using axios for api requests. Laravel 10 is running on port 8000 Vue3 is running on port 5173

I am able to successfully get csrf-cookie response (204) from axios.get('/sanctum/csrf-cookie'). However, my post request to /login is returning "419 unknown status". Response message is "CSRF token mismatch".

Error Screenshot

VUE FRONTEND:

main.js file:

import { createApp } from 'vue'
import App from './App.vue'
import axios from 'axios';

axios.defaults.headers.common["X-Requested-With"] = "XMLHttpRequest";
axios.defaults.headers.common["Content-Type"] = "application/json";
axios.defaults.headers.common["Accept"] = "application/json";
axios.defaults.withCredentials = true;

createApp(App).mount('#app')

App.vue file:

<script setup>
import axios from 'axios';
import { ref } from 'vue';

const form = ref({
  email: null,
  password: null,
})

async function onLogin(){
  await axios.get('http://localhost:8000/sanctum/csrf-cookie');
  await axios.post('http://localhost:8000/login', {
    email: form.value.email,
    password: form.value.password,
  });
}
</script>

<template>
<form @submit.prevent="onLogin">
  <div>
    <label for="email">Email: </label>
    <input type="text" v-model="form.email">
  </div>
  <div>
    <label for="password">Password: </label>
    <input type="password" v-model="form.password">
  </div>
  <div>
    <button type="submit">Login</button>
  </div>
</form>

<form></form>
</template>

LARAVEL BACKEND:

.env file:


APP_URL=http://localhost:8000
FRONTEND_URL=http://localhost:5173
SESSION_DOMAIN=localhost
SANCTUM_STATEFUL_DOMAINS=localhost:5173

Kernel.php file: api middleware group:

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

cors.php file:

<?php

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

    'allowed_methods' => ['*'],

    'allowed_origins' => ['*'],

    'allowed_origins_patterns' => [],

    'allowed_headers' => ['*'],

    'exposed_headers' => [],

    'max_age' => 0,

    'supports_credentials' => true,

];

Route in api.php:

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

There are 0 answers