Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Passport Multiple Authentication using Guards

Can we use laravel passport with different guards to authenticate APIs for two different types of users. For example we have driver app for driver user and vendor app for vendor user. Both have their different models Driver and Vendor. How can we use different guards to authenticate both types of users using Laravel Passport?

like image 623
Ahmar Arshad Avatar asked Oct 17 '18 09:10

Ahmar Arshad


People also ask

What is Guard () in Laravel?

Guards define how users are authenticated for each request. For example, Laravel ships with a session guard which maintains state using session storage and cookies. Providers define how users are retrieved from your persistent storage.

Does Laravel Passport use JWT?

Passport uses JWT authentication as standard but also implements full OAuth 2.0 authorization.


1 Answers

I managed to create multiple auths (with laravel/passport) by using a simple middlware.

Step 1: config/auth.php

Add your user classes to providers

'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'users',
    ],

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

...

'providers' => [
    'users' => [
        'driver' => 'eloquent',
        'model' => App\User::class,
    ],
    'admin_users' => [
        'driver' => 'eloquent',
        'model' => App\AdminUser::class,
    ],
    'basic_users' => [
        'driver' => 'eloquent',
        'model' => App\BasicUser::class,
    ],
],

Clean the cache via CLI

php artisan config:cache

Step 2: Create middleware

php artisan make:middleware AdminUserProvider

Open the newly created middleware in app/Http/Middleware and update the hand method like below

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

Step 3: Register your middleware

Add the newly created middleware to $routeMiddleware

protected $routeMiddleware = [
    ...
    'auth.admin' => \App\Http\Middleware\AdminUserProvider::class,
];

and make sure it's at the top of $middlewarePriority

protected $middlewarePriority = [
    \App\Http\Middleware\AdminUserProvider::class,
    ...
];

Step 4: Add middleware to route

Route::group(['middleware' => ['auth.admin','auth:api']], function() {

Step 5: LoginControllers (AdminUserController & BasicUserController)

public function login()
{
    $validatedData = request()->validate([
        'email' => 'required',
        'password' => 'required|min:6'
    ]);
    // get user object
    $user = AdminUser::where('email', request()->email)->first();
    // do the passwords match?
    if (!Hash::check(request()->password, $user->password)) {
        // no they don't
        return response()->json(['error' => 'Unauthorized'], 401);
    }
    // log the user in (needed for future requests)
    Auth::login($user);
    // get new token
    $tokenResult = $user->createToken($this->tokenName);
    // return token in json response
    return response()->json(['success' => ['token' => $tokenResult->accessToken]], 200);
}

In summary:

The login controllers use Eloquent models to get the user object and then log the user in through Auth::login($user)

Then for future requests that need authentication, the new middleware will change the api auth guard provider to the correct class.

like image 164
rharvey Avatar answered Oct 27 '22 08:10

rharvey