Mr Arman
Mr Arman

Reputation: 91

Laravel Sanctum middleware issue

I am using Laravel 11 and Sanctum to authenticate users and site administrators and I have defined two models User and Admin. After successful login the cookie is set correctly. Routes that do not require authentication just work properly. But routes for which auth:admin middleware is enabled do not work and always unauthenticated error appears in the response. The settings I have made are as follows:

config/auth.php =>

'guards' => [
    'user' => [
        'driver' => 'sanctum', // Token-based authentication for regular users
        'provider' => 'users',
    ],
    'admin' => [
        'driver' => 'sanctum', // Token-based authentication for admins
        'provider' => 'admins',
    ],
],

'providers' => [
    'users' => [
        'driver' => 'eloquent',
        'model' => App\Models\User::class,
    ],
    'admins' => [
        'driver' => 'eloquent',
        'model' => App\Models\Admin::class,
    ],
],

config/sanctum.php =>

'prefix' => 'api',
'stateful' => explode(',', env('SANCTUM_STATEFUL_DOMAINS', 'localhost:5173')),
'guard' => ['web'],
'expiration' => null,
'token_prefix' => env('SANCTUM_TOKEN_PREFIX', ''),

.env file =>

SESSION_DRIVER=cookie
SESSION_LIFETIME=120
SESSION_ENCRYPT=false
SESSION_PATH=/
SESSION_DOMAIN=localhost
SANCTUM_STATEFUL_DOMAINS=localhost:5173

Route:

Route::get('/profile', [AdminAuthController::class, 'getProfile'])->middleware('auth:admin');

I am also using axios and React on the frontend, withCredentials and withXSRFToken are also set to true, and I am also calling csrf-cookie before each request.

Cookies: enter image description here

And in getProfile method token is okay and passed in header:

public function getProfile(Request $request)
    {
        if ($request->hasCookie('laravel_token')) {
        $token = $request->cookie('laravel_token');
        dd($token);
    }
}

Result is:

"3|syHJnfoiK661gzPde0oTgFJnkFk2CT61vSNLrsus6f6868b4"

Upvotes: 0

Views: 47

Answers (0)

Related Questions