Laravel Passport
Introduction
Laravel Passport 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.
Passport or Sanctum?
Before getting started, you may wish to determine if your application would be better served by Laravel Passport or Laravel Sanctum. If your application absolutely needs to support OAuth2, then you should use Laravel Passport.
However, if you are attempting to authenticate a single-page application, mobile application, or issue API tokens, you should use Laravel Sanctum. Laravel Sanctum does not support OAuth2; however, it provides a much simpler API authentication development experience.
Installation
You may install Laravel Passport via the install:api
Artisan command:
php artisan install:api --passport
This command will publish and run the database migrations necessary for creating the tables your application needs to store OAuth2 clients and access tokens. The command will also create the encryption keys required to generate secure access tokens.
Additionally, this command will ask if you would like to use UUIDs as the primary key value of the Passport Client
model instead of auto-incrementing integers.
After running the install:api
command, add the Laravel\Passport\HasApiTokens
trait to your App\Models\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\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Passport\HasApiTokens;
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;
}
Finally, in your application's config/auth.php
configuration file, you should define an api
authentication guard and set the driver
option 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',
],
],
Deploying Passport
When deploying Passport to your application's 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 tokens. 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. Typically, this method should be called from the boot
method of your application's App\Providers\AppServiceProvider
class:
/**
* Bootstrap any application services.
*/
public function boot(): void
{
Passport::loadKeysFrom(__DIR__.'/../secrets/oauth');
}
Loading Keys From the Environment
Alternatively, you may publish Passport's configuration file using the vendor:publish
Artisan command:
php artisan vendor:publish --tag=passport-config
After the configuration file has been published, you may load your application's encryption keys by defining them as 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-----"
Upgrading Passport
When upgrading to a new major version of Passport, it's important that you carefully review the upgrade guide.
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 App\Providers\AppServiceProvider
class:
use Laravel\Passport\Passport;
Passport::hashClientSecrets();
Once enabled, all of your client secrets will only be displayable to the user immediately after they are created. Since the plain-text client secret value is never stored in the database, it is not possible to recover the secret's value if it is 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 application's App\Providers\AppServiceProvider
class:
/**
* Bootstrap any application services.
*/
public function boot(): void
{
Passport::tokensExpireIn(now()->addDays(15));
Passport::refreshTokensExpireIn(now()->addDays(30));
Passport::personalAccessTokensExpireIn(now()->addMonths(6));
}
The expires_at
columns on Passport's database tables are read-only and for display purposes only. When issuing tokens, Passport stores the expiration information within the signed and encrypted tokens. If you need to invalidate a token you should revoke it.
Overriding Default Models
You are free to extend the models used internally by Passport by defining your own model and extending the corresponding Passport model:
use Laravel\Passport\Client as PassportClient;
class Client extends PassportClient
{
// ...
}
After defining your model, you may instruct Passport to use your custom model via the Laravel\Passport\Passport
class. Typically, you should inform Passport about your custom models in the boot
method of your application's App\Providers\AppServiceProvider
class:
use App\Models\Passport\AuthCode;
use App\Models\Passport\Client;
use App\Models\Passport\PersonalAccessClient;
use App\Models\Passport\RefreshToken;
use App\Models\Passport\Token;
/**
* Bootstrap any application services.
*/
public function boot(): void
{
Passport::useTokenModel(Token::class);
Passport::useRefreshTokenModel(RefreshToken::class);
Passport::useAuthCodeModel(AuthCode::class);
Passport::useClientModel(Client::class);
Passport::usePersonalAccessClientModel(PersonalAccessClient::class);
}
Overriding Routes
Sometimes you may wish to customize the routes defined by Passport. To achieve this, you first need to ignore the routes registered by Passport by adding Passport::ignoreRoutes
to the register
method of your application's AppServiceProvider
:
use Laravel\Passport\Passport;
/**
* Register any application services.
*/
public function register(): void
{
Passport::ignoreRoutes();
}
Then, you may copy the routes defined by Passport in its routes file to your application's routes/web.php
file and modify them to your liking:
Route::group([
'as' => 'passport.',
'prefix' => config('passport.path', 'oauth'),
'namespace' => '\Laravel\Passport\Http\Controllers',
], function () {
// Passport routes...
});
Issuing Access Tokens
Using OAuth2 via authorization codes is how most developers are familiar with OAuth2. When using authorization codes, a client application will redirect a user to your server where they will either approve or deny the request to issue an access token to the client.
Managing Clients
First, developers building applications that need to interact with your application's API will need to register their application with yours by creating a "client". Typically, this consists of providing the name of their application and a URL that your application can redirect to after users approve their request for authorization.
The passport:client
Command
The simplest way to create a client is using the passport:client
Artisan command. This command may be used to create your own clients for testing your OAuth2 functionality. When you run the client
command, Passport will prompt you for more information about your client and will provide you with a client ID and secret:
php artisan passport:client
Redirect URLs
If you would like to allow multiple redirect URLs for your client, you may specify them using a comma-delimited list when prompted for the URL by the passport:client
command. Any URLs which contain commas should be URL encoded:
http://example.com/callback,http://examplefoo.com/callback
JSON API
Since your application's users will not be able to utilize the client
command, Passport provides a JSON API that you may use to create clients. This saves you the trouble of having to manually code controllers for creating, updating, and deleting clients.
However, you will need to pair Passport's JSON API with your own frontend to provide a dashboard for your users to manage their clients. Below, we'll review all of the API endpoints for managing clients. For convenience, we'll use Axios to demonstrate making HTTP requests to the endpoints.
The JSON API is guarded by the web
and auth
middleware; therefore, it may only be called from your own application. It is not able to be called from an external source.
GET /oauth/clients
This route returns all of the clients for the authenticated user. This is primarily useful for listing all of the user's clients so that they may edit or delete them:
axios.get('/oauth/clients')
.then(response => {
console.log(response.data);
});
POST /oauth/clients
This route is used to create new clients. It requires two pieces of data: the client's name
and a redirect
URL. The redirect
URL is where the user will be redirected after approving or denying a request for authorization.
When a client is created, it will be issued a client ID and client secret. These values will be used when requesting access tokens from your application. The client creation route will return the new client instance:
const data = {
name: 'Client Name',
redirect: 'http://example.com/callback'
};
axios.post('/oauth/clients', data)
.then(response => {
console.log(response.data);
})
.catch (response => {
// List errors on response...
});
PUT /oauth/clients/ \{#put-oauthclientsclient-id}{client-id}
This route is used to update clients. It requires two pieces of data: the client's name
and a redirect
URL. The redirect
URL is where the user will be redirected after approving or denying a request for authorization. The route will return the updated client instance:
const data = {
name: 'New Client Name',
redirect: 'http://example.com/callback'
};
axios.put('/oauth/clients/' + clientId, data)
.then(response => {
console.log(response.data);
})
.catch (response => {
// List errors on response...
});
DELETE /oauth/clients/ \{#delete-oauthclientsclient-id}{client-id}
This route is used to delete clients:
axios.delete('/oauth/clients/' + clientId)
.then(response => {
// ...
});
Requesting Tokens
Redirecting for Authorization
Once a client has been created, developers may use their client ID and secret to request an authorization code and access token from your application. First, the consuming application should make a redirect request to your application's /oauth/authorize
route like so:
use Illuminate\Http\Request;
use Illuminate\Support\Str;
Route::get('/redirect', function (Request $request) {
$request->session()->put('state', $state = Str::random(40));
$query = http_build_query([
'client_id' => 'client-id',
'redirect_uri' => 'http://third-party-app.com/callback',
'response_type' => 'code',
'scope' => '',
'state' => $state,
// 'prompt' => '', // "none", "consent", or "login"
]);
return redirect('http://passport-app.test/oauth/authorize?'.$query);
});
The prompt
parameter may be used to specify the authentication behavior of the Passport application.
If the prompt
value is none
, Passport will always throw an authentication error if the user is not already authenticated with the Passport application. If the value is consent
, Passport will always display the authorization approval screen, even if all scopes were previously granted to the consuming application. When the value is login
, the Passport application will always prompt the user to re-login to the application, even if they already have an existing session.
If no prompt
value is provided, the user will be prompted for authorization only if they have not previously authorized access to the consuming application for the requested scopes.
Remember, the /oauth/authorize
route is already defined by Passport. You do not need to manually define this route.
Approving the Request
When receiving authorization requests, Passport will automatically respond based on the value of prompt
parameter (if present) and may display a template to the user allowing them to approve or deny the authorization request. If they approve the request, they will be redirected back to the redirect_uri
that was specified by the consuming application. The redirect_uri
must match the redirect
URL that was specified when the client was created.
If you would like to customize the authorization approval screen, you may publish Passport's views using the vendor:publish
Artisan command. The published views will be placed in the resources/views/vendor/passport
directory:
php artisan vendor:publish --tag=passport-views
Sometimes you may wish to skip the authorization prompt, such as when authorizing a first-party client. You may accomplish this by extending the Client
model and defining a skipsAuthorization
method. If skipsAuthorization
returns true
the client will be approved and the user will be redirected back to the redirect_uri
immediately, unless the consuming application has explicitly set the prompt
parameter when redirecting for authorization:
<?php
namespace App\Models\Passport;
use Laravel\Passport\Client as BaseClient;
class Client extends BaseClient
{
/**
* Determine if the client should skip the authorization prompt.
*/
public function skipsAuthorization(): bool
{
return $this->firstParty();
}
}
Converting Authorization Codes to Access Tokens
If the user approves the authorization request, they will be redirected back to the consuming application. The consumer should first verify the state
parameter against the value that was stored prior to the redirect. If the state parameter matches then the consumer should issue a POST
request to your application to request an access token. The request should include the authorization code that was issued by your application when the user approved the authorization request:
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
Route::get('/callback', function (Request $request) {
$state = $request->session()->pull('state');
throw_unless(
strlen($state) > 0 && $state === $request->state,
InvalidArgumentException::class,
'Invalid state value.'
);
$response = Http::asForm()->post('http://passport-app.test/oauth/token', [
'grant_type' => 'authorization_code',
'client_id' => 'client-id',
'client_secret' => 'client-secret',
'redirect_uri' => 'http://third-party-app.com/callback',
'code' => $request->code,
]);
return $response->json();
});
This /oauth/token
route will return a JSON response containing access_token
, refresh_token
, and expires_in
attributes. The expires_in
attribute contains the number of seconds until the access token expires.
Like the /oauth/authorize
route, the /oauth/token
route is defined for you by Passport. There is no need to manually define this route.
JSON API
Passport also includes a JSON API for managing authorized access tokens. You may pair this with your own frontend to offer your users a dashboard for managing access tokens. For convenience, we'll use Axios to demonstrate making HTTP requests to the endpoints. The JSON API is guarded by the web
and auth
middleware; therefore, it may only be called from your own application.
GET /oauth/tokens
This route returns all of the authorized access tokens that the authenticated user has created. This is primarily useful for listing all of the user's tokens so that they can revoke them:
axios.get('/oauth/tokens')
.then(response => {
console.log(response.data);
});
DELETE /oauth/tokens/ \{#delete-oauthtokenstoken-id}{token-id}
This route may be used to revoke authorized access tokens and their related refresh tokens:
axios.delete('/oauth/tokens/' + tokenId);
Refreshing Tokens
If your application issues short-lived access tokens, users will need to refresh their access tokens via the refresh token that was provided to them when the access token was issued:
use Illuminate\Support\Facades\Http;
$response = Http::asForm()->post('http://passport-app.test/oauth/token', [
'grant_type' => 'refresh_token',
'refresh_token' => 'the-refresh-token',
'client_id' => 'client-id',
'client_secret' => 'client-secret',
'scope' => '',
]);
return $response->json();
This /oauth/token
route will return a JSON response containing access_token
, refresh_token
, and expires_in
attributes. The expires_in
attribute contains the number of seconds until the access token expires.
Revoking Tokens
You may revoke a token by using the revokeAccessToken
method on the Laravel\Passport\TokenRepository
. You may revoke a token's refresh tokens using the revokeRefreshTokensByAccessTokenId
method on the Laravel\Passport\RefreshTokenRepository
. These classes may be resolved using Laravel's service container:
use Laravel\Passport\TokenRepository;
use Laravel\Passport\RefreshTokenRepository;
$tokenRepository = app(TokenRepository::class);
$refreshTokenRepository = app(RefreshTokenRepository::class);
// Revoke an access token...
$tokenRepository->revokeAccessToken($tokenId);
// Revoke all of the token's refresh tokens...
$refreshTokenRepository->revokeRefreshTokensByAccessTokenId($tokenId);
Purging Tokens
When tokens have been revoked or expired, you might want to purge them from the database. Passport's included passport:purge
Artisan command can do this for you:
# Purge revoked and expired tokens and auth codes...
php artisan passport:purge
# Only purge tokens expired for more than 6 hours...
php artisan passport:purge --hours=6
# Only purge revoked tokens and auth codes...
php artisan passport:purge --revoked
# Only purge expired tokens and auth codes...
php artisan passport:purge --expired
You may also configure a scheduled job in your application's routes/console.php
file to automatically prune your tokens on a schedule:
use Laravel\Support\Facades\Schedule;
Schedule::command('passport:purge')->hourly();
Authorization Code Grant With PKCE
The Authorization Code grant with "Proof Key for Code Exchange" (PKCE) is a secure way to authenticate single page applications or native applications to access your API. This grant should be used when you can't guarantee that the client secret will be stored confidentially or in order to mitigate the threat of having the authorization code intercepted by an attacker. A combination of a "code verifier" and a "code challenge" replaces the client secret when exchanging the authorization code for an access token.
Creating the Client
Before your application can issue tokens via the authorization code grant with PKCE, you will need to create a PKCE-enabled client. You may do this using the passport:client
Artisan command with the --public
option:
php artisan passport:client --public
Requesting Tokens
Code Verifier and Code Challenge
As this authorization grant does not provide a client secret, developers will need to generate a combination of a code verifier and a code challenge in order to request a token.
The code verifier should be a random string of between 43 and 128 characters containing letters, numbers, and "-"
, "."
, "_"
, "~"
characters, as defined in the RFC 7636 specification.
The code challenge should be a Base64 encoded string with URL and filename-safe characters. The trailing '='
characters should be removed and no line breaks, whitespace, or other additional characters should be present.
$encoded = base64_encode(hash('sha256', $code_verifier, true));
$codeChallenge = strtr(rtrim($encoded, '='), '+/', '-_');
Redirecting for Authorization
Once a client has been created, you may use the client ID and the generated code verifier and code challenge to request an authorization code and access token from your application. First, the consuming application should make a redirect request to your application's /oauth/authorize
route:
use Illuminate\Http\Request;
use Illuminate\Support\Str;
Route::get('/redirect', function (Request $request) {
$request->session()->put('state', $state = Str::random(40));
$request->session()->put(
'code_verifier', $code_verifier = Str::random(128)
);
$codeChallenge = strtr(rtrim(
base64_encode(hash('sha256', $code_verifier, true))
, '='), '+/', '-_');
$query = http_build_query([
'client_id' => 'client-id',
'redirect_uri' => 'http://third-party-app.com/callback',
'response_type' => 'code',
'scope' => '',
'state' => $state,
'code_challenge' => $codeChallenge,
'code_challenge_method' => 'S256',
// 'prompt' => '', // "none", "consent", or "login"
]);
return redirect('http://passport-app.test/oauth/authorize?'.$query);
});
Converting Authorization Codes to Access Tokens
If the user approves the authorization request, they will be redirected back to the consuming application. The consumer should verify the state
parameter against the value that was stored prior to the redirect, as in the standard Authorization Code Grant.
If the state parameter matches, the consumer should issue a POST
request to your application to request an access token. The request should include the authorization code that was issued by your application when the user approved the authorization request along with the originally generated code verifier:
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
Route::get('/callback', function (Request $request) {
$state = $request->session()->pull('state');
$codeVerifier = $request->session()->pull('code_verifier');
throw_unless(
strlen($state) > 0 && $state === $request->state,
InvalidArgumentException::class
);
$response = Http::asForm()->post('http://passport-app.test/oauth/token', [
'grant_type' => 'authorization_code',
'client_id' => 'client-id',
'redirect_uri' => 'http://third-party-app.com/callback',
'code_verifier' => $codeVerifier,
'code' => $request->code,
]);
return $response->json();
});
Password Grant Tokens
We no longer recommend using password grant tokens. Instead, you should choose a grant type that is currently recommended by OAuth2 Server.
The OAuth2 password grant allows your other first-party clients, such as a mobile application, to obtain an access token using an email address / username and password. This allows you to issue access tokens securely to your first-party clients without requiring your users to go through the entire OAuth2 authorization code redirect flow.
To enable the password grant, call the enablePasswordGrant
method in the boot
method of your application's App\Providers\AppServiceProvider
class:
/**
* Bootstrap any application services.
*/
public function boot(): void
{
Passport::enablePasswordGrant();
}
Creating a Password Grant Client
Before your application can issue tokens via the password grant, you will need to create a password grant client. You may do this using the passport:client
Artisan command with the --password
option. If you have already run the passport:install
command, you do not need to run this command:
php artisan passport:client --password