When to Reach for Sanctum vs. Passport
Laravel ships with two first‑party packages for API authentication: Sanctum and Passport. Both are solid, but they solve slightly different problems. Understanding the trade‑offs early saves you from refactoring later.
| Feature | Sanctum | Passport |
|---------|---------|----------|
| Token type | Simple personal access tokens (plain text) and SPA cookie‑based tokens | Full OAuth2 server (JWT‑style access tokens) |
| Setup complexity | Minimal – a single service provider and migration | Moderate – requires installing Laravel\Passport, running passport:install, and configuring the OAuth server |
| Use case | Single‑page apps, mobile apps, or micro‑services that need quick token issuance without a full OAuth flow | Public APIs, third‑party integrations, or any scenario where you need scopes, token revocation, and refresh tokens |
| Token storage | Database table personal_access_tokens (hashed) | OAuth tables (oauth_clients, oauth_access_tokens, etc.) |
| Token format | Random 60‑character string, stored hashed | JWT (or opaque) signed with the server’s private key |
If your product is a B2B SaaS exposing an API to partner developers, Passport is usually the right choice. For internal mobile apps or SPA front‑ends that you control, Sanctum wins on simplicity.
Setting Up Sanctum – The Minimal Path
- Install
composer require laravel/sanctum php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider" php artisan migrate - Add the Middleware to
apigroup inapp/Http/Kernel.php:protected $middlewareGroups = [ 'api' => [ \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class, 'throttle:api', \Illuminate\Routing\Middleware\SubstituteBindings::class, ], ]; - Create Tokens in your login controller:
public function login(Request $request) { $user = User::where('email', $request->email)->first(); if (! $user || ! Hash::check($request->password, $user->password)) { return response()->json(['message' => 'Invalid credentials'], 401); } $token = $user->createToken('mobile-app')->plainTextToken; return response()->json(['access_token' => $token]); } - Protect Routes with
auth:sanctum:Route::middleware('auth:sanctum')->get('/user', function (Request $request) { return $request->user(); });
Security Checklist for Sanctum
- Hash tokens: Sanctum stores the plain text only once; it saves a hash in the DB, so a breach doesn’t expose raw tokens.
- Rate‑limit login: Use Laravel’s
throttlemiddleware on the login route. - Revoke on logout:
$request->user()->tokens()->delete(); - Use HTTPS everywhere – tokens are bearer credentials.
Setting Up Passport – Full OAuth2
- Install
Thecomposer require laravel/passport php artisan migrate php artisan passport:installinstallcommand creates encryption keys and a default client for password grants. - Service Provider (Laravel 9+ auto‑discovers, otherwise add to
config/app.php). - Configure Auth Guard in
config/auth.php:'guards' => [ 'api' => [ 'driver' => 'passport', 'provider' => 'users', ], ], - Add
HasApiTokenstrait toUsermodel:use Laravel\Passport\HasApiTokens; class User extends Authenticatable { use HasApiTokens, Notifiable; } - Issue Tokens using password grant:
public function login(Request $request) { $http = new \GuzzleHttp\Client; $response = $http->post(url('/oauth/token'), [ 'form_params' => [ 'grant_type' => 'password', 'client_id' => config('passport.password_client.id'), 'client_secret' => config('passport.password_client.secret'), 'username' => $request->email, 'password' => $request->password, 'scope' => '*', ], ]); return json_decode((string) $response->getBody(), true); } - Protect Routes with
auth:api:Route::middleware('auth:api')->get('/profile', function (Request $request) { return $request->user(); });
Passport Security Tips
- Use short‑lived access tokens (e.g., 1 hour) and refresh tokens for renewal.
- Scope your tokens – define granular abilities in
AuthServiceProvider:Passport::tokensCan([ 'order-create' => 'Create orders', 'order-read' => 'Read order data', ]); - Revoke compromised tokens with
$token->revoke();. - Rotate keys periodically (
passport:keys --force). - Enable PKCE for native mobile apps – it mitigates interception of the authorization code.
Decision Matrix for Startup Teams
| Criterion | Sanctum | Passport | |-----------|---------|----------| | Time to market | < 1 day | 2–3 days (keys, clients) | | Third‑party developers | Not ideal – no OAuth flow | Designed for external devs | | Token revocation granularity | Per‑user token only | Per‑token, per‑client, per‑scope | | Refresh tokens | Not built‑in | Built‑in, standard flow | | Complexity overhead | Low | Medium‑High | | Compliance (e.g., GDPR, PCI) | Sufficient if you control the client | Better for regulated environments due to revocation & scopes |
If you’re building an internal API that serves your own mobile app and admin panel, start with Sanctum. You can later migrate to Passport if you open the API to partners – the migration path is straightforward because both store tokens in the users table (Sanctum) or OAuth tables (Passport). Keep the business logic decoupled from the authentication layer, and you won’t be locked in.
Real‑World Migration Checklist
- Add both packages to the project (they can coexist).
- Introduce a feature flag to toggle which guard protects a route.
- Write integration tests for both
auth:sanctumandauth:api. - Gradually move external clients to the Passport flow while internal clients stay on Sanctum.
- Monitor token usage – Laravel Telescope or a custom log can surface unexpected token lifetimes.
- Deprecate Sanctum once all external clients have migrated, then clean up migrations and service providers.
Takeaway
- Start simple: Sanctum is perfect for first‑party apps and rapid prototyping.
- Scale responsibly: Switch to Passport when you need OAuth2 features like scopes, refresh tokens, or third‑party developer access.
- Plan migration early: Keep authentication concerns isolated so the switch doesn’t ripple through business code.
By matching the authentication strategy to your product’s audience and security requirements, you avoid unnecessary complexity while staying ready for future growth.
- Laravel
- Api
- Security
- Authentication