Search code examples
phplaravelmiddlewarelaravel-9

auth()->user() returns null in Laravel 9, Passport Api middleware


I'm using Passport package for authentation and the auth is working fine in routes and controllers.

I want to make a custom middleware for Admin chekcing, But auth()->user() returns null.

This is my middleware:

public function handle(Request $request, Closure $next)
{
    if (Auth::user() && Auth::user()->is_admin == 1){
        return $next($request);
    }
    
    return response()->json(['message' => 'Not Allowed'], Response::HTTP_FORBIDDEN);
}

and this is my Karnel.php:

protected $routeMiddleware = [
    'auth' => \App\Http\Middleware\Authenticate::class,
    'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
    'auth.session' => \Illuminate\Session\Middleware\AuthenticateSession::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' => \App\Http\Middleware\ValidateSignature::class,
    'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
    'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
    'admin' => \App\Http\Middleware\AdminCheck::class,
];

Solution

  • When you do Auth::user(), it will use the default guard in your config/auth.php, which I think currently its web. You can change the default to api if you want:

    'defaults' => [
        'guard' => 'api',
        'passwords' => 'users',
    ],
    

    OR alternatively you can Auth::guard to use a specific guard. e.g. Auth::guard('api')->user(). Documentation here: https://laravel.com/docs/10.x/authentication#accessing-specific-guard-instances

    So your middleware will look like this:

    public function handle(Request $request, Closure $next)
    {
        if (Auth::guard('api')->user() && Auth::guard('api')->user()->is_admin == 1){
            return $next($request);
        }
        
        return response()->json(['message' => 'Not Allowed'], Response::HTTP_FORBIDDEN);
    }