'Laravel passport: assigning the scopes to access token overriding oauth/token route

I am working on a Laravel project. I am using Laravel Passport for API authentication. I am trying to assign the scopes to the access token based on the user role after the user has logged in or generated the access token through oauth/token route with passport grant-type. How can I override it?

I cannot do this as mentioned in the documentation.

$token = $user->createToken('My Token', ['place-orders'])->accessToken;

Because it is explicitly generating the token. It seems like I have to write my own login method to use that. How can I override the oauth/token route instead?



Solution 1:[1]

I'm not exactly sure of your use case, but if you are authenticating over OAuth, you would include your scopes in the /authorize GET request as per the OAuth spec.

i.e.
https://localhost/oauth/authorize?response_type=code&client_id=abc123 &scope=myfirstscope,mysecondscope etc.

See OAuth spec here:

https://datatracker.ietf.org/doc/html/rfc6749#section-4.1.1

You can also define a default scope with:

Passport::tokensCan([
    'place-orders' => 'Place orders',
    'check-status' => 'Check order status',
]);
 
Passport::setDefaultScope([
    'check-status',
    'place-orders',
]);

https://laravel.com/docs/9.x/passport#default-scope

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Harvey Dobson