How to use Multiple Passport Personal Access Clients for different Auth Guards

590 views Asked by At

Passport 10:0 Laravel 9.0 php 8.1

Description

Thankyou in advance. My application has four user types and uses multiple guards for each, i.e, admins, agents, companies, and normal users. All of these guards use API authentication via personal access clients, and tokens are generated for each user type like so; $user->createToken('TOKEN_NAME')->accessToken; This worked well, until I ran into an issue where two users of different types, say Admin and Company, having the same id, say 1, could share tokens. The admin user would pass company middleware and vice versa. The issue is discussed in this #Question

The solution proposed in that discussion is to create separate personal access clients for each guard, and to use the different clients to generate access tokens, which makes sense. To generate access tokens using the different clients, however, i have to clear the resolved ClientRepository instance and register a new singleton instance, like so;

use Laravel\Passport\ClientRepository;

App::clearResolvedInstance(ClientRepository::class);
app()->singleton(ClientRepository::class, function () {
    return new ClientRepository(client_id, null); // client secret ignored for this use case
});
$token = $user->createToken('TOKEN-NAME')->accessToken;

Is there a cleaner way of doing this? Is it possible to set or override a ClientRepository property on the Admin::class model such that every call to createToken() by an Admin instance uses the set client?

0

There are 0 answers