Nuxt project throws CSRF token mismatch 419 error while trying to login users through Laravel Sanctum

4k views Asked by At

Structure of the project:

2 folders namely api and client, where api is used for laravel installation and client refers to the nuxt project.

Laravel (v-8.00) setups:

This is what I have in .env file for the session variables

SESSION_DRIVER=cookie
SESSION_LIFETIME=120
SESSION_DOMAIN=127.0.0.1
SANCTUM_STATEFUL_DOMAINS=127.0.0.1:3000

cors.php contains the following

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

'allowed_methods' => ['*'],

'allowed_origins' => ['*'],

'allowed_origins_patterns' => [],

'allowed_headers' => ['*'],

'exposed_headers' => false,

'max_age' => true,

'supports_credentials' => true,

No changes made to sanctum.php and it contains

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

Nuxt Setups

.env file contains:

PORT=3000
HOST=127.0.0.1
BASE_URL=http://127.0.0.1:3000
API_URL=http://127.0.0.1:8000

nuxt.config.js contains:

modules: [
    '@nuxtjs/axios',
    '@nuxtjs/auth-next',
    '@nuxtjs/pwa',
    '@nuxtjs/dotenv',
],
/*
** Axios module configuration
** See https://axios.nuxtjs.org/options
*/
axios: {
    baseUrl: process.env.API_URL,
    credentials: true,
},

auth: {
    strategies: {
    cookie: {
        cookie: {
        name: 'XSRF-TOKEN',
        }
    },
        'laravelSanctum': {
        provider: 'laravel/sanctum',
        url: process.env.API_URL
        },
    },
    redirect: {
        login: '/login',
        logout: '/login',
        callback: '/login',
        home: '/'
    }
},

Login.vue has

    data() {
        return {
            form: {
                email: '',
                password: ''
            },
            errors: {}
        }
    },

    methods: {
        async submit () {
            this.$auth.loginWith('laravelSanctum', { data: this.form })
            .then(response => {
                this.$router.push(`/`)
            })
            .catch(({response}) => {
                this.errors = response.data.errors
            })

        }
    },

Responses

This is what I am getting in response when trying to log a user in:

enter image description here

enter image description here

enter image description here

2

There are 2 answers

0
Hadayat Niazi On

419 error means that your session domain is not correctly set. If you are using localhost set your domain like below

SESSION_DOMAIN=.localhost

Remove . before localhost

SESSION_DOMAIN=localhost
1
P. K. Tharindu On

I know this is an old question. But I just ran into this myself and thought I'd share what worked for me.

Apparently, setting SESSION_DOMAIN=127.0.0.1 throws a 419 error with "CSRF token mismatch".

However, if you set it to SESSION_DOMAIN=localhost, it works just fine.