Laravel OAuth2 with Passport
February 22, 2024
•
15 min read
Introduction
Laravel Passport provides a full OAuth2 server implementation. It's the recommended way to implement API authentication for applications that need to serve third-party clients.
Installation
// Install Passport
composer require laravel/passport
// Run migrations
php artisan migrate
// Generate keys
php artisan passport:install
Configuration
// User model
class User extends Model
{
use HasApiTokens;
}
// auth.php config
'guards' => [
'api' => [
'driver' => 'passport',
'provider' => 'users',
],
],
Grant Types
// Password Grant (for mobile apps)
POST /oauth/token
{
"grant_type": "password",
"client_id": "client-id",
"client_secret": "client-secret",
"username": "user@example.com",
"password": "password",
"scope": "*"
}
// Client Credentials (for server-to-server)
POST /oauth/token
{
"grant_type": "client_credentials",
"client_id": "client-id",
"client_secret": "client-secret"
}
// Authorization Code (for web apps)
// Redirect to /oauth/authorize
Protecting Routes
// Protect routes
Route::middleware('auth:api')->group(function () {
Route::get('/user', function (Request $request) {
return $request->user();
});
});
// Using scopes
Route::middleware('auth:api', 'scope:read-profile')->get('/profile', function () {
// Only users with read-profile scope can access
});
// Define scopes in AuthServiceProvider
Passport::tokensCan([
'read-profile' => 'Read profile',
'write-profile' => 'Update profile',
]);
Summary
Laravel Passport makes implementing OAuth2 straightforward. Use it for secure API authentication with support for multiple grant types.
For more Laravel tutorials, see API Authentication.