Home > database >  CSRF Token Mismatch On Axios Post Requests In Laravel
CSRF Token Mismatch On Axios Post Requests In Laravel

Time:11-07

I am working on a project with a React front-end and a Laravel back-end. I am trying to set up my authentication system. I am utilizing SPA authentication using Sanctum. I am successfully utilizing the sanctum/csrf-cookie route, where the XSRF-Token cookie is given. When I then try to follow that up with a login, I get a 419 error, CSRF token mismatch. There is no XSRF-Token. What is interesting is that if I do a get request, as in the 'testing' route below, the XSRF cookie is present. However, when I do a post request, as in posting to the login route, the cookie is not present and I get a 419 error.

I am running this locally right now. The front-end is running at localhost:3000, with the back-end running at localhost:8888. Here are various relevant segments of code.

LoginForm.js

let data = {
  email: e.target[0].value,
  password: e.target[1].value
}
axios.get('http://localhost:8888/sanctum/csrf-cookie')
.then((res) => {
  axios.post('http://localhost:8888/login', data)
  .then((res) => {
    axios.get('http://localhost:8888/user')
  })
})

Kernel.php

protected $middleware = [
        \App\Http\Middleware\TrustProxies::class,
        \Fruitcake\Cors\HandleCors::class,
        \App\Http\Middleware\PreventRequestsDuringMaintenance::class,
        \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
        \App\Http\Middleware\TrimStrings::class,
        \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
        \Illuminate\Session\Middleware\StartSession::class,
        \Illuminate\Session\Middleware\AuthenticateSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
    ];

    protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
            \App\Http\Middleware\HandleInertiaRequests::class,
        ],

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

    protected $routeMiddleware = [
        'auth' => \App\Http\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
        'can' => \Illuminate\Auth\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
        'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
        'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
    ];

.env

SESSION_DRIVER=cookie
SESSION_DOMAIN=localhost
SANCTUM_STATEFUL_DOMAINS=localhost:3000

Bootstrap.js

axios = require('axios');

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

Web.php

Route::get('/testing', function () {
    return "Testing.";
});

Route::post('/login', function(Request $request) {
    $credentials = $request->validate([
        'email' => ['required', 'email'],
        'password' => ['required'],
    ]);

    if (Auth::attempt($credentials)) {
        $request->session()->regenerate();
        $id = Auth::id();
        $user = User::find($id);
        return $user;
    }

    return back()->withErrors([
        'email' => 'The provided credentials do not match our records.',
    ]);
});

Sanctum.php

'stateful' => explode(',', env('SANCTUM_STATEFUL_DOMAINS', sprintf(
    '%s%s',
    'localhost,localhost:3000,localhost:8888,
    Sanctum::currentApplicationUrlWithPort()
))),

Cors.php

'supports_credentials' => true,

CodePudding user response:

Let's review one by one what is needed to apply SPA authentication using sanctum.

  • First, they must share same top-level domains, however each could be hosted on subdomains, on you case you are using localhost, so this should be fine.
  • Next, you should configure which domains your SPA will be making requests from. SANCTUM_STATEFUL_DOMAINS. If you are accessing your application via a URL that includes a port (127.0.0.1:8000), you should ensure that you include the port number with the domain. Here, it seems you are missing the port.
  • Next, you should add middleware as mentioned in https://laravel.com/docs/9.x/sanctum#sanctum-middleware which seems you have already done it.
  • Next fix cors issue: First, you need to set supports_credentials to be true on config/cors.php. Next, you should enable the withCredentials option on your application's global axios instance. axios.defaults.withCredentials = true;
  • Finally, you should ensure your application's session cookie domain configuration supports any subdomain of your root domain. SESSION_DOMAIN, looks like you have already set localhost here.

Overall, it seems you need to fix to things:

  • you need to add port if you are accessing it from port.
  • you need to set supports_credentials to true on config/cors.php

For more detail, you can follow: https://laravel.com/docs/9.x/sanctum#spa-authentication

CodePudding user response:

To make things easier, I would setup a CLIENT_URL environment variable, in your .env:

CLIENT_URL=http://localhost:3000

Make sure that your client application is present in your allowed_origins in your cors.php:

'allowed_origins' => [env('CLIENT_URL')],

And that your sanctum config also takes it into account:

/* sanctum.php */
    'stateful' => explode(',', env('SANCTUM_STATEFUL_DOMAINS', sprintf(
        '%s%s%s',
        'localhost,localhost:3000,127.0.0.1,127.0.0.1:8000,::1',
        env('CLIENT_URL') ? ','.parse_url(env('CLIENT_URL'), PHP_URL_HOST) : ''
    ))),

If you still want to use SANCTUM_STATEFUL_DOMAINS environment variable, add the protocol to the URL:

SANCTUM_STATEFUL_DOMAINS=http://localhost:3000
  • Related