I am using Laravel Sanctum for SPA authentication. My SPA is react and resides in same repo as of Laravel. It means that i am using Laravel React UI scaffolding.
My First concern is that while visiting login page of my SPA app, i see XSRF-TOKEN
and app_session
cookie without sending request to sanctum/csrf-cookie
Question: Why cookies are getting generated without calling csrf-cookie endpoint?
Can it be that Laravel generates it by default?
Secondly, calls to login and csrf-cookie are working fine but /user
API is failing
My Environment file .env
has below conf:
SESSION_DRIVER=cookie
SESSION_LIFETIME=120
# localhost
SANCTUM_STATEFUL_DOMAINS='app.vm.com'
SESSION_DOMAIN='vm.com'
sanctum.php
has below conf:
return [
'stateful' => explode(',', env('SANCTUM_STATEFUL_DOMAINS', 'localhost,127.0.0.1,127.0.0.1:8000,::1')),
'expiration' => null,
'middleware' => [
'verify_csrf_token' => App\Http\Middleware\VerifyCsrfToken::class,
'encrypt_cookies' => App\Http\Middleware\EncryptCookies::class,
],
'prefix' => 'api',
'guard' => 'api',
];
cors.php
has below conf:
return [
'paths' => ['api/*'],
'allowed_methods' => ['*'],
'allowed_origins' => ['*'],
'allowed_origins_patterns' => [],
'allowed_headers' => ['*'],
'exposed_headers' => [],
'max_age' => 0,
'supports_credentials' => true,
];
kernel.php
has also required changes:
'api' => [
EnsureFrontendRequestsAreStateful::class,
throttle:60,1',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
My routes web.php
looks like as:
$spa = function () {
return view('app');
};
Route::get('/{view?}', $spa)->where('view', '(.*)')->name('catchall');
api.php
route file looks like as below:
Route::middleware('auth:sanctum')->group(function () {
Route::get('/user', function (Request $request) {
return $request->user();
});
});
Route::post('/login', 'LoginController@login');
Route::post('/logout', 'LoginController@logout');
Please assist in solving assisting 401 error for /user
end point. I have followed many tutorials but no luck.