skip to Main Content

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' => AppHttpMiddlewareAuthenticate::class,
    'auth.basic' => IlluminateAuthMiddlewareAuthenticateWithBasicAuth::class,
    'auth.session' => IlluminateSessionMiddlewareAuthenticateSession::class,
    'cache.headers' => IlluminateHttpMiddlewareSetCacheHeaders::class,
    'can' => IlluminateAuthMiddlewareAuthorize::class,
    'guest' => AppHttpMiddlewareRedirectIfAuthenticated::class,
    'password.confirm' => IlluminateAuthMiddlewareRequirePassword::class,
    'signed' => AppHttpMiddlewareValidateSignature::class,
    'throttle' => IlluminateRoutingMiddlewareThrottleRequests::class,
    'verified' => IlluminateAuthMiddlewareEnsureEmailIsVerified::class,
    'admin' => AppHttpMiddlewareAdminCheck::class,
];

2

Answers


  1. 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);
    }
    
    Login or Signup to reply.
  2. I would suggest instead of using Auth::guard(‘api’) everywhere use api middleware directly on the routes in api.php or web.php.

    you can do like this:

     Route::group(['middleware' => ['api', 'othermiddleware']], function () {
      
     //put your route here.
    
    });
    
    // for auth route
    
      Route::group(['middleware' => ['auth:api', 'othermiddleware']], function () {
      
     //put your route which require auth checking.
    
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search