dusterio/lumen-passport

Using multiple guards

salvationarinze opened this issue · 3 comments

Since laravel passport defaults to the api guard. I have multiple user types that I want to authenticate seperately. Please how do I go about it?

oza75 commented

Did you find how to use multiple guard ?

still no updates?

sorry for that much late response but the issue is handled by following the steps below !

  • lets assume that we've 3 models/providers can be authenticate the system -> User(customer), Admin and Vendor
  • each provider has its own route by its token

// HERE IS MY AUTH.PHP CONFIG FILE -> i set api guard as default


return [
    'defaults' => [
        'guard' => 'api',
    ],

    'guards' => [
        'api' => [
            'driver' => 'passport',
            'provider' => 'users', // default
        ],
    ],

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

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

        'vendors' => [
            'driver' => 'eloquent',
            'model' => \App\Models\Vendor::class
        ],
    ]
];

with this step the User instance is able to achieve related api with its bearer token , but other can't.

now define a middleware to update the guard in conf ! (i ll show only the AdminMiddleware)

here is my AdminMiddleware !

 public function handle($request, Closure $next)
    {
        config(['auth.guards.api.provider' => 'admins']);
        return $next($request);
    }

the only thing we do here is let the app be aware of updated provider due to its guards . and we set the provider as admins to check the correct table/model.

then for sure initialize your middleware in bootstrap/app.php

$app->routeMiddleware([
    ....
    'auth' => App\Http\Middleware\Authenticate::class,
    'admin' => App\Http\Middleware\AdminMiddleware::class,
    ...
]);

now we re able to test it out !, when we want to let users to be able to consume api we should use default auth:api middleware like :


$router->group(['middleware' =>  'auth:api'], function () use ($router) {
    return $request->user(); // will return Authenticated User Instance || null
});

and for admin ->

// DO NOT FORGET TO ADD MIDDLEWARE HERE !
$router->group(['middleware' => ['admin', 'auth:api']], function () use ($router) {
    return $request->user(); // will return Authenticated Admin Instance || null
});

code with love :)