Laravel Passport is a package that simplifies the implementation of OAuth authorization in a Laravel application very easy. I’ve been making use of this quite heavily in a project that I’m in the process of building.
What makes it quite nice is that it hooks into Laravel’s authentication ecosystem, and makes as trivial as request()->user()
to access the currently-authenticated user.
However, OAuth clients have the ability to be able to authenticate using the client_credentials
OAuth grant type. There
are certain requests in which I need to know the OAuth client that is currently authenticated, and could find no way
of hooking this into a request()->user()
call.
So, I built a very small & simple package that provides an auth guard that provides this functionality.
The package is available at https://github.com/garbetjie/laravel-auth-passport-client, but here’s a summary of how to use it:
Configuration
Firstly, configure the auth guard:
<?php
// in config/auth.php
return [
'guards' => [
'client' => [
'driver' => 'passport-client',
'provider' => 'client',
]
],
'providers' => [
'client' => [
'driver' => 'eloquent',
'model' => Laravel\Passport\Client::class,
]
]
];
Usage
When wanting to fetch the OAuth client that authenticated, simply call the ->user() method on the request object with the name of the configured guard:
<?php
class MyController extends \App\Http\Controllers\Controller
{
public function myAction(\Illuminate\Http\Request $request)
{
$client = request()->user('client');
// or
$client = $request->user('client');
}
}