Laravel Passport is a popular OAuth2 server for Laravel applications, which makes it easy to implement API authentication. It provides support for various grant types, including personal access tokens. Below is a step-by-step guide on how to use Laravel Passport for API authentication with personal access tokens:
Install Laravel Passport using Composer:
bashcomposer require laravel/passport
Run the Passport migrations to create the necessary database tables:
bashphp artisan migrate
Install Passport using the install
Artisan command:
bashphp artisan passport:install
This command will generate encryption keys and create the necessary database tables for Passport.
Make your User model implement the HasApiTokens
trait:
phpuse Laravel\Passport\HasApiTokens;
class User extends Authenticatable
{
use HasApiTokens, Notifiable;
// ...
}
In your AuthServiceProvider
, add the following lines to the boot
method:
phpuse Laravel\Passport\Passport;
public function boot()
{
$this->registerPolicies();
Passport::routes();
}
In your routes/api.php
file, define the routes that should be protected by Passport:
phpRoute::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
To create a personal access token, you can use the createToken
method on a user instance:
php$user = User::find(1);
$token = $user->createToken('Token Name')->accessToken;