Laravel Passport
Introduction
Laravel already makes it easy to perform authentication via traditional login forms, but what about APIs? APIs typically use tokens to authenticate users and do not maintain session state between requests. Laravel makes API authentication a breeze using Laravel Passport, which provides a full OAuth2 server implementation for your Laravel application in a matter of minutes. Passport is built on top of the League OAuth2 server that is maintained by Andy Millington and Simon Hamp.
This documentation assumes you are already familiar with OAuth2. If you do not know anything about OAuth2, consider familiarizing yourself with the general terminology and features of OAuth2 before continuing.
Upgrading Passport
When upgrading to a new major version of Passport, it's important that you carefully review the upgrade guide.
Installation
To get started, install Passport via the Composer package manager:
composer require laravel/passport "~9.0"
The Passport service provider registers its own database migration directory with the framework, so you should migrate your database after installing the package. The Passport migrations will create the tables your application needs to store clients and access tokens:
php artisan migrate
Next, you should run the passport:install
command. This command will create the encryption keys needed to generate secure access tokens. In addition, the command will create "personal access" and "password grant" clients which will be used to generate access tokens:
php artisan passport:install
If you would like to use UUIDs as the primary key value of the Passport Client
model instead of auto-incrementing integers, please install Passport using the uuids
option.
After running the passport:install
command, add the Laravel\Passport\HasApiTokens
trait to your App\User
model. This trait will provide a few helper methods to your model which allow you to inspect the authenticated user's token and scopes:
<?php
namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Passport\HasApiTokens;
class User extends Authenticatable
{
use HasApiTokens, Notifiable;
}
Next, you should call the Passport::routes
method within the boot
method of your AuthServiceProvider
. This method will register the routes necessary to issue access tokens and revoke access tokens, clients, and personal access tokens:
<?php
namespace App\Providers;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Gate;
use Laravel\Passport\Passport;
class AuthServiceProvider extends ServiceProvider
{
/**
* The policy mappings for the application.
*
* @var array
*/
protected $policies = [
'App\Model' => 'App\Policies\ModelPolicy',
];
/**
* Register any authentication / authorization services.
*
* @return void
*/
public function boot()
{
$this->registerPolicies();
Passport::routes();
}
}
Finally, in your config/auth.php
configuration file, you should set the driver
option of the api
authentication guard to passport
. This will instruct your application to use Passport's TokenGuard
when authenticating incoming API requests:
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'passport',
'provider' => 'users',
],
],
Client UUIDs
You may run the passport:install
command with the --uuids
option present. This flag will instruct Passport that you would like to use UUIDs instead of auto-incrementing integers as the Passport Client
model's primary key values. After running the passport:install
command with the --uuids
option, you will be given additional instructions regarding disabling Passport's default migrations:
php artisan passport:install --uuids
Frontend Quickstart
In order to use the Passport Vue components, you must be using the Vue JavaScript framework. These components also use the Bootstrap CSS framework. However, even if you are not using these tools, the components serve as a valuable reference for your own frontend implementation.
Passport ships with a JSON API that you may use to allow your users to create clients and personal access tokens. However, it can be time consuming to code a frontend to interact with these APIs. So, Passport also includes pre-built Vue components you may use as an example implementation or starting point for your own implementation.
To publish the Passport Vue components, use the vendor:publish
Artisan command:
php artisan vendor:publish --tag=passport-components
The published components will be placed in your resources/js/components
directory. Once the components have been published, you should register them in your resources/js/app.js
file:
Vue.component(
'passport-clients',
require('./components/passport/Clients.vue').default
);
Vue.component(
'passport-authorized-clients',
require('./components/passport/AuthorizedClients.vue').default
);
Vue.component(
'passport-personal-access-tokens',
require('./components/passport/PersonalAccessTokens.vue').default
);
Prior to Laravel v5.7.19, appending .default
when registering components results in a console error. An explanation for this change can be found in the Laravel Mix v4.0.0 release notes.
After registering the components, make sure to run npm run dev
to recompile your assets. Once you have recompiled your assets, you may drop the components into one of your application's templates to get started creating clients and personal access tokens:
<passport-clients></passport-clients>
<passport-authorized-clients></passport-authorized-clients>
<passport-personal-access-tokens></passport-personal-access-tokens>
Deploying Passport
When deploying Passport to your production servers for the first time, you will likely need to run the passport:keys
command. This command generates the encryption keys Passport needs in order to generate access token. The generated keys are not typically kept in source control:
php artisan passport:keys
If necessary, you may define the path where Passport's keys should be loaded from. You may use the Passport::loadKeysFrom
method to accomplish this:
/**
* Register any authentication / authorization services.
*
* @return void
*/
public function boot()
{
$this->registerPolicies();
Passport::routes();
Passport::loadKeysFrom('/secret-keys/oauth');
}
Additionally, you may publish Passport's configuration file using php artisan vendor:publish --tag=passport-config
, which will then provide the option to load the encryption keys from your environment variables:
PASSPORT_PRIVATE_KEY="-----BEGIN RSA PRIVATE KEY-----
<private key here>
-----END RSA PRIVATE KEY-----"
PASSPORT_PUBLIC_KEY="-----BEGIN PUBLIC KEY-----
<public key here>
-----END PUBLIC KEY-----"
Migration Customization
If you are not going to use Passport's default migrations, you should call the Passport::ignoreMigrations
method in the register
method of your AppServiceProvider
. You may export the default migrations using php artisan vendor:publish --tag=passport-migrations
.
Configuration
Client Secret Hashing
If you would like your client's secrets to be hashed when stored in your database, you should call the Passport::hashClientSecrets
method in the boot
method of your AppServiceProvider
:
Passport::hashClientSecrets();
Once enabled, all of your client secrets will only be shown one time when your client is created. Since the plain-text client secret value is never stored in the database, it is not possible to recover if lost.
Token Lifetimes
By default, Passport issues long-lived access tokens that expire after one year. If you would like to configure a longer / shorter token lifetime, you may use the tokensExpireIn
, refreshTokensExpireIn
, and personalAccessTokensExpireIn
methods. These methods should be called from the boot
method of your AuthServiceProvider
:
/**
* Register any authentication / authorization services.
*
* @return void
*/
public function boot()
{
$this->registerPolicies();
Passport::routes();
Passport::tokensExpireIn(now()->addDays(15));
Passport::refreshTokensExpireIn(now()->addDays(30));
Passport::personalAccessTokensExpireIn(now()->addMonths(6));
}