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
When you do
Auth::user()
, it will use the default guard in yourconfig/auth.php
, which I think currently itsweb
. You can change the default toapi
if you want: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-instancesSo your middleware will look like this:
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: