Setting up and configuring Laravel Passport for OAuth2 server functionality involves a few steps. Laravel Passport is an OAuth2 server that provides a full implementation of the OAuth2 server specification. Here's a step-by-step guide along with an example:
First, install Laravel Passport using Composer:
bashcomposer require laravel/passport
Run the Passport install command to set up the necessary database tables and migrations:
bashphp artisan passport:install
In your User model (typically located at app/Models/User.php
), use the Laravel\Passport\HasApiTokens
trait:
phpuse Laravel\Passport\HasApiTokens;
class User extends Authenticatable
{
use HasApiTokens, Notifiable;
//...
}
In the AuthServiceProvider
(typically located at app/Providers/AuthServiceProvider.php
), import Passport
and register the necessary routes:
phpuse Laravel\Passport\Passport;
public function boot()
{
$this->registerPolicies();
Passport::routes();
}
In your config/auth.php
file, ensure that the API guard uses the Passport driver:
php'guards' => [
'api' => [
'driver' => 'passport',
'provider' => 'users',
],
],
In the app/Http/Kernel.php
file, include the \Laravel\Passport\Http\Middleware\CreateFreshApiToken::class
middleware in the web
group:
phpprotected $middlewareGroups = [
'web' => [
// ...
\Laravel\Passport\Http\Middleware\CreateFreshApiToken::class,
],
// ...
];
Run the database migrations to apply the changes:
bashphp artisan migrate
To create an OAuth client, use the passport:client
Artisan command. This command will prompt you for the necessary information:
bashphp artisan passport:client
Once configured, you can use Passport to protect routes and authenticate users. Here's a simple example of protecting an API route:
phpRoute::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
Make sure to consult the Laravel Passport documentation for any updates or changes in the configuration process.
=== Happy Coding :)