Kritim Yantra
Jun 01, 2025
Imagine you're building an apartment building (your Laravel application). To keep residents safe, you need a sophisticated access system that allows:
Laravel Passport is that access system - a powerful OAuth2 server that manages API authentication securely and professionally. Let's break it down in simple terms!
Passport adds professional-grade security to your Laravel API through:
Passport | Sanctum |
---|---|
Full OAuth2 implementation | Simple API token authentication |
Best for third-party apps | Best for your own SPA/mobile apps |
Complex permission systems | Basic token-based access |
Choose Passport when: You're building something like "Login with Google/Facebook" or allowing other developers to connect to your API.
composer require laravel/passport
php artisan install:api --passport
php artisan migrate
php artisan passport:keys
class User extends Authenticatable implements OAuthenticatable
{
use HasApiTokens; // Adds token superpowers to users
}
// config/auth.php
'guards' => [
'api' => [
'driver' => 'passport', // Use Passport for API auth
'provider' => 'users',
],
],
Authorization Code Grant
The standard "Login with..." flow:
Password Grant (Legacy)
User provides email/password directly to get token
Note: Not recommended for new projects
Client Credentials Grant
For machine-to-machine communication:
$token = Http::post('/oauth/token', [
'grant_type' => 'client_credentials',
'client_id' => 'your-id',
'client_secret' => 'your-secret',
'scope' => 'read-data'
]);
Personal Access Tokens
Users generate their own tokens (like API keys):
// User creates a token
$token = $user->createToken('My Token')->accessToken;
Add protection to routes using middleware:
// Protect route with authentication
Route::get('/profile', function() {
return auth()->user();
})->middleware('auth:api');
// Require specific permissions
Route::post('/orders', function() {
// Create order
})->middleware(['auth:api', 'scope:orders:create']);
Scopes define what a token can do:
// Define scopes in AppServiceProvider
Passport::tokensCan([
'user:read' => 'View your profile',
'orders:create' => 'Place new orders',
'orders:status' => 'Check order status',
]);
// Request scopes during authorization
$query = http_build_query([
'scope' => 'user:read orders:status'
]);
Check scopes in your controllers:
if (auth()->user()->tokenCan('orders:create')) {
// User has order creation permission
}
Passport provides testing helpers:
// Authenticate as user with specific scopes
Passport::actingAs(
User::factory()->create(),
['user:read']
);
// Make test API call
$response = $this->get('/api/user');
Imagine building a weather API accessed by mobile apps:
App developer registers:
php artisan passport:client --password
Gets client ID: 98765432
, secret: abc123secret
Mobile app requests token:
axios.post('/oauth/token', {
client_id: 98765432,
client_secret: 'abc123secret',
username: 'user@example.com',
password: 'password',
scope: 'weather:read'
})
API responds with token:
{
"access_token": "eyJhbGciOi...",
"expires_in": 31536000
}
App accesses protected data:
axios.get('/api/forecast', {
headers: {
Authorization: `Bearer eyJhbGciOi...`
}
})
// In AppServiceProvider
Passport::tokensExpireIn(now()->addDays(15));
$user->tokens()->each->revoke();
php artisan passport:purge
Laravel Passport gives you enterprise-grade API security with:
Remember:
"Passport is for when you need professional API security - like giving different keys to residents, guests, and staff in your digital apartment building."
Now that you understand the basics, you're ready to implement secure API authentication in your Laravel applications! What will you build with your new security superpower? ๐
Transform from beginner to Laravel expert with our personalized Coaching Class starting June 10, 2025. Limited enrollment ensures focused attention.
1-hour personalized coaching
Build portfolio applications
Industry-standard techniques
Interview prep & job guidance
Complete your application to secure your spot
Thank you for your interest in our Laravel mentorship program. We'll contact you within 24 hours with next steps.
No comments yet. Be the first to comment!
Please log in to post a comment:
Sign in with Google