Handling API Authentication with Passport or Sanctum
Laravel offers two first-party packages for API authentication: Passport, a full OAuth2 server, and Sanctum, a lighter token-based system built for SPAs, mobile apps, and simple token authentication.
Choosing Between Them
| Feature | Sanctum | Passport |
|---|---|---|
| Best for | SPAs, mobile apps, simple APIs | Full OAuth2 (third-party apps, scopes) |
| Setup complexity | Low | Higher |
| Token type | Personal access tokens | OAuth2 access/refresh tokens |
Setting Up Sanctum
composer require laravel/sanctum
php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
php artisan migrate
Add the HasApiTokens trait to the User model, then issue a token after login:
$token = $user->createToken('api-token')->plainTextToken;
Protecting Routes
Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
return $request->user();
});
Once requests are authenticated, the next concern is usually stopping any single client from overwhelming the API with too many calls.
Ready to master Laravel Training Course?
Join Uncodemy's hands-on Laravel program and build real, production-ready applications.
