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.
Quick Install on Recent Laravel Versions
From Laravel 11 onward, API scaffolding is not included by default. One Artisan command creates routes/api.php, installs Sanctum and publishes its migration:
php artisan install:api
# or, to set up Passport instead of Sanctum
php artisan install:api --passport
The manual steps shown above still work and are what you will see in older projects.
A Complete Token Login Flow
- The client sends email and password to a login endpoint.
- The server checks the credentials and creates a token.
- The client stores the token and sends it in the
Authorization: Bearerheader. - Protected routes use
auth:sanctumto identify the user. - On logout, the current token is deleted so it can no longer be used.
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\ValidationException;
Route::post('/login', function (Request $request) {
$data = $request->validate([
'email' => 'required|email',
'password' => 'required',
'device_name' => 'required',
]);
$user = User::where('email', $data['email'])->first();
if (! $user || ! Hash::check($data['password'], $user->password)) {
throw ValidationException::withMessages(['email' => 'Invalid credentials.']);
}
return ['token' => $user->createToken($data['device_name'], ['orders:read'])->plainTextToken];
});
Route::middleware('auth:sanctum')->post('/logout', function (Request $request) {
$request->user()->currentAccessToken()->delete();
return response()->noContent();
});
Limiting What a Token Can Do
The second argument to createToken lists abilities. Check them in code before performing sensitive actions:
if ($request->user()->tokenCan('orders:read')) {
return $request->user()->orders;
}
abort(403);
Passport offers the same idea through OAuth2 scopes, which also appear on the consent screen when a third-party app requests access.
Give each token only the abilities its client needs. A reporting script that only reads orders should not receive a token that can delete them, so a leaked token does far less damage.
SPA Cookie Mode Versus Tokens
If your Vue or React front end is served from the same top-level domain as the API, Sanctum can authenticate it with Laravel's normal session cookie instead of tokens. The SPA first calls /sanctum/csrf-cookie, then logs in through a regular login route. List the front-end domain in the SANCTUM_STATEFUL_DOMAINS setting and allow credentials in your CORS configuration. This avoids keeping long-lived tokens in browser storage.
Mobile apps and external scripts cannot share cookies, so they use the token flow shown earlier.
Safe Defaults Checklist
- Serve the API only over HTTPS so tokens are never sent in plain text.
- Set a token expiry through the
expirationoption inconfig/sanctum.php, and prune old tokens on a schedule. - Throttle the login route to slow down password guessing.
- Give each device its own named token so a lost phone can be revoked alone.
- Choose Passport only when you truly need OAuth2, such as letting outside developers build apps on your platform.
- Return the plain-text token only once, at creation. Sanctum stores a hash of it, so it cannot be shown again; ask the user to create a new one if it is lost.
Ready to master Laravel Training Course?
Join Uncodemy's hands-on Laravel program and build real, production-ready applications.