laravel/passport
Laravel Passport provides a full OAuth2 server for Laravel, making API authentication simple with access tokens, personal access tokens, and client credentials. Officially maintained, with extensive docs and integrations for securing first- and third-party APIs.
## Getting Started
### Minimal Setup
1. **Installation**:
```bash
composer require laravel/passport
php artisan passport:install
Passport::routes() in AuthServiceProvider.First Use Case:
auth:api middleware.
Route::middleware('auth:api')->group(function () {
Route::get('/user', function (Request $request) {
return $request->user();
});
});
Passport::token() in tests or manual scenarios:
$token = Passport::actingAs($user)->createToken('API Token')->accessToken;
Key Files:
config/auth.php: Ensure api guard uses passport driver.app/Providers/AuthServiceProvider.php: Verify Passport::routes() is called.$client = \Laravel\Passport\Client::find(1);
$token = $client->accessToken;
$response = Http::withToken($token)->get('api/endpoint');
/oauth/authorize with client_id and redirect_uri.
Exchange code for token via /oauth/token endpoint.$token = $user->createToken('My PAT')->accessToken;
$user->tokens()->delete();
$token = $user->createToken('Admin Access', ['admin', 'read']);
public function handle(Request $request, Closure $next) {
if (!$request->user()->tokenCan('admin')) {
abort(403);
}
return $next($request);
}
Passport::actingAs($user);
// or for clients
Passport::actingAsClient($client);
$response = $this->withHeaders([
'Authorization' => 'Bearer ' . $token,
])->get('/api/endpoint');
$response->assertOk();
User model implements Laravel\Passport\HasApiTokens:
use Laravel\Passport\HasApiTokens;
class User extends Authenticatable {
use HasApiTokens, Notifiable;
}
findForPassport if using non-standard auth identifiers:
public static function findForPassport($identifier) {
return static::where('email', $identifier)->first();
}
Laravel\Passport\Client for custom logic:
class CustomClient extends \Laravel\Passport\Client {
public function isInternal() {
return $this->name === 'Internal Service';
}
}
AuthServiceProvider:
Passport::useClientModel(CustomClient::class);
Passport::tokensExpireIn(CarbonInterval::hours(1));
Passport::refreshTokensExpireIn(CarbonInterval::days(30));
Passport::personalAccessTokensExpireIn(CarbonInterval::never());
HandlePersonalAccessTokens:
Passport::personalAccessTokensCanSee([YourMiddleware::class]);
php artisan passport:purge
Laravel\Passport\Token to add fields (e.g., ip_address):
class CustomToken extends \Laravel\Passport\Token {
protected $fillable = ['ip_address'];
}
Passport::ignoreRoutes();
Passport::ignoreMigrations();
user_id matches client_id (fixed in v13.7.1).if ($token->user_id === $client->id) {
throw new \League\OAuth2\Server\Exception\OAuthServerException(
'User impersonation detected'
);
}
passport:hashphp artisan passport:hash after passport:install causes token generation failures.php artisan passport:hash
// Wrong: Scopes not saved
$token = $user->createToken('Test', ['scope1']);
// Correct:
$token = $user->createToken('Test')->accessToken;
$token->scopes()->attach(['scope1']);
$token->save();
TokenGuard may fail if auth.guard is misconfigured.config/auth.php:
'guards' => [
'api' => [
'driver' => 'passport',
'provider' => 'users',
],
],
PASSPORT_CLIENT_SECRET=your_secure_secret
passport:install after custom migrations may cause conflicts.oauth_clients table schema in UPGRADE.md and merge changes manually.Bearer <token>).tinker to inspect):
php artisan tinker
>>> \Laravel\Passport\Token::find(1)->expires_at
Passport::enableDebugMode();
oauth-server exceptions.redirect_uri matches registered URIs (case-sensitive).grant_types include required flows (e.g., authorization_code).oauth_access_tokens:
Schema::table('oauth_access_tokens', function (Blueprint $table) {
$table->index('user_id');
$table->index('client_id');
});
Passport::purge() periodically to clean revoked tokens.League\OAuth2\Server\Grant\GrantInterface:
class CustomGrant implements GrantInterface {
public function respondToAccessTokenRequest() { /* ... */ }
}
AuthServiceProvider:
Passport::grantType(CustomGrant::class);
TokenRepository to use Redis or another store:
Passport::tokens()->useCustomRepository(CustomTokenRepository::class);
Passport::tokensGranted(function ($user, $token) {
// Log token issuance
});
tokensCreated, tokensRefreshed, tokensRevoked.Passport::exceptionHandling
How can I help you explore Laravel packages today?