Nuxt-Laravel-Sanctum CSRF token mismatch 419 error

Viewed 6086

I have a Nuxt-Laravel-Sanctum CSRF token mismatch 419 error while Laravel is hosted on a server and Nuxt is on localhost on a PC. I have uploaded my Laravel project for getting API on api.repairtofix.com.

And I am trying to log in from localhost in my pc from Nuxt. While clicking on the login button I get the following error.

{message: "CSRF token mismatch.", exception: "Symfony\Component\HttpKernel\Exception\HttpException",…}

Login method

login() {
    this.$auth.loginWith('laravelSanctum', { 
        data: this.form 
    })
    .then(response => console.log(response))
    .catch(error => console.log(response))
}

.env

APP_URL=http://api.repairtofix.com
SESSION_DOMAIN=api.repairtofix.com
SANCTUM_STATEFUL_DOMAINS=.repairtofix.com,localhost:3000

Kernel.php

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

sanctum.php

'stateful' => explode(',', env('SANCTUM_STATEFUL_DOMAINS', 
    'api.repairtofix.com,localhost,localhost:3000,127.0.0.1,127.0.0.1:8000,::1'
)),

cors.php

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

api.php

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

// register
Route::get('register', function(Request $request){
    $user = User::create([
        'name' => $request->name,
        'email' => $request->email,
        'password' => bcrypt($request->password)
    ]);

    return $user;
});

// login
Route::post('login', function(Request $request){
    $credentials = $request->only('email', 'password');
    if(!auth()->attempt($credentials)){
        throw ValidationException::withMessages([
            'email' => 'Invalid credentials'
        ]);
    }

    $request->session()->regenerate();
    return response()->json(null, 201);
});

// logout
Route::post('logout', function(Request $request){
    auth()->guard('web')->logout();
    $request->session()->invalidate();
    $request->session()->regenerateToken();
    return response()->json(null, 201);
});

nuxt.config.js

modules: [
    '@nuxtjs/axios',
    '@nuxtjs/pwa',
    '@nuxtjs/auth-next',
    '@nuxtjs/toast',
],

auth:{
    strategies: {
        'laravelSanctum': {
            provider: 'laravel/sanctum',
            url: 'http://api.repairtofix.com',
            endpoints: {
                login: {
                    url: '/api/login'
                },
                logout: {
                    url: '/api/logout'
                },
                user: {
                    url: '/api/user'
                },
            },
            user: {
                property: false
            }
        },
    },
    redirect: {
        login: "/login",
        logout: "/",
        home: "/"
    }
},
3 Answers

I guess you are using SPA authentication with sanctum, both your server and client has to be on the same domain. The client(localhost) and your api is on different domain.

docs

In order to authenticate, your SPA and API must share the same top-level domain. However, they may be placed on different subdomains.

In my case, Axios credentials were not set to true in nuxt.config file, also the text is case sensitive


  axios: {
    baseUrl: 'http://localhost:8000',
    credentials: true,
  },

It is maybe a little bit late but others in future. 1-check the api/config/sanctum in laravel and make the ports correct on localhost:xxxx and 127.0.0.1:xxxx 2-on .env file make coorection for SANCTUM_STATEFUL_DOMAINS=localhost:xxxx

Related