I can’t get the authenticated user in Laravel app. I have this codes:
config/auth.php
return [
'defaults' => [
'guard' => 'sanctum',
'passwords' => 'users',
],
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'members',
],
'api' => [
'driver' => 'session',
'provider' => 'users',
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => AppModelsUser::class,
],
'members' => [
'driver' => 'eloquent',
'model' => DomainCustomerModelsMember::class,
]
],
];
config/sanctum.php
return [
'stateful' => // ...
'guard' => null,
'expiration' => null,
'middleware' => [
'verify_csrf_token' => AppHttpMiddlewareVerifyCsrfToken::class,
'encrypt_cookies' => AppHttpMiddlewareEncryptCookies::class,
],
];
routes/web.php
Route::prefix('auth')->group(function ($router) {
Route::post('login', [AuthController::class, 'loginAsMember']);
// ...
});
Route::middleware('lang')->group(function ($router) {
// ...
Route::prefix('{locale}')->group(function () {
Route::middleware('auth')->group(function () {
Route::get('webshop/basket', [PublicBasketController::class, 'show'])->name(RouteName::BASKET);
});
});
// ...
});
I have an Authenticate middleware where I try to catch the user and if it’s not logged in I redirect to the custom login url.
class Authenticate extends Middleware
{
protected function redirectTo($request)
{
if (! $request->expectsJson()) {
return route(RouteName::LOGIN, ['local' => App::getLocale()]);
}
}
}
In here if I dd(Auth::user())
it receives null.
But if I dd($request)
I see this:
+cookies: SymfonyComponentHttpFoundationInputBag {#46 ▼
#parameters: array:4 [ ▼
"XSRF-TOKEN" => "MbJcRadlrAJ2mDhECvWwMFyIe0fyqrQUO83K2U1K"
"laravel_session" => "mqWuCqTRD074TOvOPMGRfIIgP0jxKLyoD8VyyWCS"
]
}
+headers: SymfonyComponentHttpFoundationHeaderBag {#49 ▼
#headers: array:13 [▼
"cookie" => array:1 [▼
0 => "_ga=... ▶"
]
"accept-language" => array:1 [▶]
"accept-encoding" => array:1 [▶]
"referer" => array:1 [▶]
"accept" => array:1 [▶]
"user-agent" => array:1 [▶]
"upgrade-insecure-requests" => array:1 [▶]
"cache-control" => array:1 [▶]
"pragma" => array:1 [▶]
"connection" => array:1 [▶]
"host" => array:1 [▶]
"content-length" => array:1 [▶]
"content-type" => array:1 [▶]
]
#cacheControl: array:1 [▼
"no-cache" => true
]
}
So there is an valid XSRF-TOKEN cookie, but Laravel did not identify the user.
How can I get user by XSRF-TOKEN cookie?