Laravel Passport is a full OAuth2 server implementation for Laravel. It allows you to easily set up and use OAuth2 for secure API authentication. Here's a step-by-step guide on how to set up Laravel Passport with an example:
Run the following command to install Passport via Composer:
bashcomposer require laravel/passport
Run the migrations to create the necessary tables for Passport:
bashphp artisan migrate
Install Passport using the following Artisan command:
bashphp artisan passport:install
This command creates the encryption keys needed to generate secure access tokens.
In your AuthServiceProvider
located at app/Providers/AuthServiceProvider.php
, make sure to call Passport::routes()
within the boot
method:
phpuse Laravel\Passport\Passport;
public function boot()
{
$this->registerPolicies();
Passport::routes();
}
In your User
model, use the Laravel\Passport\HasApiTokens
trait:
phpuse Laravel\Passport\HasApiTokens;
class User extends Authenticatable
{
use HasApiTokens, Notifiable;
// ...
}
In your config/auth.php
file, make sure the api
guard uses the passport
driver:
php'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'passport',
'provider' => 'users',
],
],
Run the following command to create a client:
bashphp artisan passport:client
This command will prompt you to choose the type of client (e.g., "Password grant client"). You can choose according to your needs.
Protect your API routes using the auth:api
middleware. For example:
phpRoute::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
You can use tools like Postman or cURL to request access tokens. For password grant, you'll need to send a POST request to /oauth/token
with the client credentials and user credentials.
These resources will provide more in-depth information on using Laravel Passport and handling various authentication scenarios.
=== Happy Coding :)