So it's been several hours I couldn't figure out the issue even reading through and trying any possible solution available on the internet. I'm using Laravel 7.x with Vue js and struggling with Sanctum SPA authentication.
Login request works fine which is using Auth::routes() defined in web.php
but, any requests made to APIs defined in api.php under auth:sanctum middleware returns 401. For example, call to fetch the user object fails with status 401:
Here is the Request Header:
This is web.php
This is api.php
Here is the stateful object in sanctum.php
'stateful' => explode(',', env('SANCTUM_STATEFUL_DOMAINS', 'localhost,127.0.0.1,127.0.0.1:8000')),
On vue.js side, I've set the withCredentials flag to true:
window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
window.axios.defaults.withCredentials = true;
in cors.php, suports_credentials flag is also set to true
and, here is my Kernel.php
/**
* The application's route middleware groups.
*
* @var array
*/
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
// \Illuminate\Session\Middleware\AuthenticateSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
'api' => [
EnsureFrontendRequestsAreStateful::class,
'throttle:60,1',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
];
EnsureFrontendRequestsAreStateful::class
and why is it in the Kernel file namespace ? Since you want statefull sessions, why not use theweb
group instead of theapi
one ? if it is juste for the prefix/api
in the url, you can change that even usingweb
group. – Vivanvivarium