Laravel Passport vs Sanctum: Which One Do You Actually Need?
I ran every Sanctum and Passport flow on a clean Laravel 13 project. Sanctum fits most apps. Passport is for apps that act on behalf of your users.
For most Laravel apps, Sanctum is the right pick. It covers your own SPA, your own mobile app and personal API tokens. Passport exists so that someone else's application can act on behalf of your users through OAuth2. In 2026 that includes MCP clients, which is the one new reason a small app might need it.
I didn't want to write that from memory. So I installed both on a clean Laravel 13.39 project (Sanctum 4.3.3, Passport 13.10.0, PHP 8.3) and ran every flow this post compares with curl: SPA cookie auth, mobile tokens, token abilities, client credentials, the authorization code flow with PKCE, refresh tokens, and both packages in one app. All output below is real.
Two things surprised me. Neither installer finishes the job. install:api leaves Sanctum's SPA support switched off, and install:api --passport writes routes for a guard it never creates.
The comparison, from what I measured
| Sanctum 4.3.3 | Passport 13.10.0 | |
|---|---|---|
| Built for | Your own SPA, mobile app and API keys | Third-party apps acting for your users |
| Install command | php artisan install:api |
php artisan install:api --passport |
| Composer packages added | 1 | 13 |
| Database tables | 1 | 5 |
| Token format | Opaque string, 50 characters | Signed JWT, about 1,040 characters |
| What the database stores | SHA-256 hash of the token | Token ID, scopes, revoked flag |
| Default token lifetime | Never expires | 1 year |
| First-party SPA auth | Session cookies, no token | laravel_token cookie |
| OAuth2 grants | None | Authorization code with PKCE, client credentials, device, refresh |
| Password grant | Not applicable | Off until you enable it |
What install:api sets up, and what it leaves to you
A fresh Laravel 13 app has no Sanctum and no routes/api.php. Both have been opt-in since Laravel 11, when the API routes file moved behind install:api.
Sanctum
php artisan install:api
It took about 7 seconds. It added one package, published config/sanctum.php and the personal_access_tokens migration, created routes/api.php and registered it in bootstrap/app.php. The last line of output tells you to add the Laravel\Sanctum\HasApiTokens trait to your User model. For tokens, that's the only manual step.
SPA cookie auth needs a second step the installer never mentions. You have to call statefulApi() yourself:
// bootstrap/app.php
->withMiddleware(function (Middleware $middleware): void {
$middleware->statefulApi();
})
I left it out on purpose to see what happens. The CSRF cookie request returned 204, the login returned 204, and then /api/user returned 401. Nothing in that sequence points at the missing line.
Passport
php artisan install:api --passport
This pulled in 13 packages (League OAuth2 Server 9.4.1, lcobucci/jwt, phpseclib and others), generated an RSA key pair in storage/, ran five migrations and created a personal access client. Then my first request failed:
Auth guard [api] is not defined. InvalidArgumentException [500]
The generated routes/api.php uses auth:api, but the installer never adds that guard to config/auth.php. The Passport docs list it as a manual step, along with an interface on the User model:
// config/auth.php
'guards' => [
'web' => ['driver' => 'session', 'provider' => 'users'],
'api' => ['driver' => 'passport', 'provider' => 'users'],
],
use Laravel\Passport\Contracts\OAuthenticatable;
use Laravel\Passport\HasApiTokens;
class User extends Authenticatable implements OAuthenticatable
{
use HasApiTokens, HasFactory, Notifiable;
}
Passport 13 also ships no consent screen. Its upgrade guide calls it "a headless OAuth2 library" now, so for the authorization code flow you write the view yourself.
Sanctum in practice
Tokens for mobile apps, CLIs and extensions
This is the route I used for a mobile-style login:
Route::post('/tokens', function (Request $request) {
$request->validate(['email' => 'required|email', 'password' => 'required', 'device' => 'required']);
if (! Auth::validate($request->only('email', 'password'))) {
return response()->json(['message' => 'Invalid credentials'], 422);
}
$user = User::where('email', $request->email)->first();
return ['token' => $user->createToken($request->device, ['posts:read'])->plainTextToken];
});
And what came back:
{"token":"1|iD0buu3XS7neS1ucmpsMz19MgaUuD1hfwIYPfHDM68b30d4b"}
The 1 is the row ID. The next 40 characters are random, and the last 8 (68b30d4b) are a CRC32B checksum of those 40. The database never stores the token itself, only a SHA-256 hash of everything after the pipe. I hashed it with shasum -a 256 and compared it to the token column. They matched. So a leaked database dump gives an attacker nothing they can send in a header.
(Set SANCTUM_TOKEN_PREFIX if you want tokens that secret scanners can recognise. The comment in config/sanctum.php points to GitHub's secret scanning for exactly this.)
Abilities worked once I registered the middleware aliases, which install:api also skips:
$middleware->alias([
'abilities' => \Laravel\Sanctum\Http\Middleware\CheckAbilities::class,
'ability' => \Laravel\Sanctum\Http\Middleware\CheckForAnyAbility::class,
]);
A token with only posts:read got 200 on GET /api/posts and 403 on POST /api/posts, with "Invalid ability provided." in the body. Inside controllers and policies, $request->user()->tokenCan('posts:write') runs the same check.
Change one default before production. Sanctum tokens never expire unless you set expiration in config/sanctum.php or pass a date as the third argument to createToken(). I created a token that expired a second earlier and got a 401, then cleared it with php artisan sanctum:prune-expired --hours=0. The browser extension case works the same way, and I've covered it in the Chrome extension architecture guide.
Cookie auth for your own SPA
For a first-party SPA, Sanctum uses no tokens at all. It's Laravel's normal session with CSRF protection. With the SPA on localhost:3000 and the API on localhost:8741:
GET /sanctum/csrf-cookie 204
POST /login (no X-XSRF-TOKEN header) 419
POST /login (with X-XSRF-TOKEN header) 204
GET /api/user 200
GET /api/user (no Origin or Referer) 401
GET /api/user (Origin: app.example.com) 401
Sanctum only treats a request as stateful when its Origin or Referer matches the stateful list in config/sanctum.php (set through SANCTUM_STATEFUL_DOMAINS). Send a valid session cookie from an unlisted origin and you get a plain 401 with no hint why. The SPA and the API also have to share a top-level domain, according to the Sanctum docs.
One more catch. The CSRF token changes when the session regenerates at login, so the SPA has to read the XSRF-TOKEN cookie fresh for every request. My first logout attempt reused the pre-login value and got a 419. Axios handles this for you once withXSRFToken is on.
If your frontend is an Inertia app (like the Vue 3 and Inertia setup I wrote about), you don't need any of this. Inertia talks to ordinary web routes, so plain session auth already covers it.
The logout route that breaks for SPA users
This is the usual Sanctum logout, and the docs show the same call for revoking the current token:
$request->user()->currentAccessToken()->delete();
It works for token clients. For a cookie-authenticated SPA request, currentAccessToken() returns a TransientToken, and the call fails:
Call to undefined method Laravel\Sanctum\TransientToken::delete()
If one route serves both kinds of client, branch on the token type:
use Laravel\Sanctum\PersonalAccessToken;
Route::post('/logout', function (Request $request) {
$token = $request->user()->currentAccessToken();
if ($token instanceof PersonalAccessToken) {
$token->delete();
} else {
Auth::guard('web')->logout();
$request->session()->invalidate();
$request->session()->regenerateToken();
}
return response()->noContent();
})->middleware('auth:sanctum');
I ran it both ways. The SPA logout returned 204 and the next /api/user call got 401. The token client got the same result.
Passport in practice
Personal access tokens
$user->createToken('cli', ['posts:read'])->accessToken;
This returned a 1,043-character JWT signed with RS256. Decoded, the payload carries the client ID as aud, the user ID as sub, the scopes, and an exp exactly one year out. I had set Passport::tokensExpireIn(CarbonInterval::days(15)), but personal access tokens follow a separate setting, personalAccessTokensExpireIn(), which defaults to a year.
The token is a JWT, but Passport still checks the database. It stores each token's ID with a revoked flag and reads it on every request. I revoked the token in Tinker and the very next call got 401.
Client credentials for machine-to-machine
php artisan passport:client --client --name="Reporting service"
INFO New client created successfully.
Client ID .. 01a18149-eabc-735a-80c4-509ee705e404
Client Secret .. zB3uyD1F82YqOY7XF4f9opGzTiA8HR9BYjMm6z1h
WARN The client secret will not be shown again, so don't lose it!
Take that warning literally. The secret is stored as a bcrypt hash.
Posting grant_type=client_credentials to /oauth/token returned a token with expires_in: 1296000, the 15 days I configured. Routes for these clients use the EnsureClientIsResourceOwner middleware instead of auth:api, and the two don't mix. The client token got 401 on /api/user, and a user's personal access token got 401 on the client route.
Authorization code with PKCE, the reason Passport exists
This is the flow behind buttons like "Connect to GitHub". Three parties take part: the partner app, the user's browser and your Laravel app. The step numbers match the curl run further down.
To run it, I created a public client (no secret) for a partner dashboard:
php artisan passport:client --public --name="Partner dashboard" --redirect_uri="http://localhost:4000/callback"
Then I registered the scopes and the consent view in AppServiceProvider::boot():
Passport::tokensCan([
'posts:read' => 'Read your posts',
'posts:write' => 'Create and update posts',
]);
Passport::authorizationView(fn ($parameters) => view('oauth.authorize', $parameters));
The view only has to post back the state, the client ID and the one-time auth_token:
<h1>{{ $client->name }} wants to access your account</h1>
<ul>@foreach ($scopes as $scope)<li>{{ $scope->description }}</li>@endforeach</ul>
<form method="post" action="{{ route('passport.authorizations.approve') }}">
@csrf
<input type="hidden" name="state" value="{{ $request->state }}">
<input type="hidden" name="client_id" value="{{ $client->getKey() }}">
<input type="hidden" name="auth_token" value="{{ $authToken }}">
<button>Authorize</button>
</form>
A real one also needs a deny button, which sends a DELETE to the same route. I scripted the rest of the flow with curl. Trimmed output:
== 1. authorize while logged out
302 -> http://127.0.0.1:8742/login
== 2. log in
302 -> http://127.0.0.1:8742/oauth/authorize?client_id=01a1814a-27c0-73b2-8002-cd6ebbaab18f&code_challenge=aYhWazrPUpjm3RlktTFRTEfYawf3KvLWGdyxmNOnLLE&code_challenge_method=S256...
== 3. consent screen
<h1>Partner dashboard wants to access your account</h1>
<li>Read your posts</li>
== 4. approve
http://localhost:4000/callback?code=def502000a3464443e8dbd586f2a53b482a7e85ce93f7d40893a07...
== 5. exchange code without the verifier
{"error":"invalid_request", ... "hint":"Check the `code_verifier` parameter"}
== 6. exchange code with the verifier
{'token_type': 'Bearer', 'expires_in': 1296000, 'access_token': '1043 chars', 'refresh_token': '804 chars'}
== 7. call the API
{"posts":[]} [200]
== 8. refresh
{'token_type': 'Bearer', 'expires_in': 1296000, 'access_token': '1040 chars', 'refresh_token': '804 chars'}
== 9. old access token after refresh
{"message":"Unauthenticated."} [401]
== 11. reuse the first refresh token
{"error":"invalid_grant","error_description":"The refresh token is invalid.","hint":"Token has been revoked"}
PKCE is enforced, so no verifier means no token. Refreshing revokes both the old access token and the old refresh token, which makes a stolen refresh token good for one use at most. And a second authorization request for the same scopes skipped the consent screen and went straight back with a new code, because the user had already granted them.
The password grant is off
passport:client --password happily creates a client. Using it returns this:
{"error":"unsupported_grant_type","error_description":"The authorization grant type is not supported by the authorization server.", ...}
You have to call Passport::enablePasswordGrant(), and the docs no longer recommend that grant. If your plan was Passport so a mobile app can trade an email and password for a token, Sanctum's token route above does exactly that with far less machinery.
When Passport is the right call
Passport earns its 13 packages in a few cases:
- Other developers build apps on your API. They register a client, your users see your consent screen, and you can revoke one app without touching the others. That's the authorization code flow above, and Sanctum has nothing like it.
- MCP clients connect to your app. The Laravel MCP docs recommend Passport, because OAuth 2.1 is what the MCP spec documents and what most clients support. The same page says to stay on Sanctum until you need a client that only supports OAuth. I went through the scope limits in securing a Laravel MCP server.
- Devices without a browser. Passport 13 supports the device authorization grant, the "open this URL and type this code" flow you see on TVs and CLIs.
- Services you don't control need credentials. Client credentials give each one its own ID, secret and scopes. For your own internal services, a Sanctum token on a service user is simpler.
Everything else (your SPA, your mobile app, a browser extension, an API key page in account settings) belongs on Sanctum. The rest of the API design, versioning and rate limiting included, is the same either way, and I've covered it in Laravel API development best practices.
Ask one question of any new requirement. Will someone outside your team ever see a consent screen? If not, you don't need Passport.
Can you run both in one app?
The obvious approach fails at once. Adding both HasApiTokens traits to the User model is a fatal error:
Trait method Laravel\Sanctum\HasApiTokens::tokens has not been applied as App\Models\User::tokens,
because of collision with Laravel\Passport\HasApiTokens::tokens
What does work is Passport's trait on the model plus Sanctum for SPA cookie auth only, because cookie auth doesn't need Sanctum's trait. My SPA got 200 from an auth:sanctum route while Passport tokens kept working on auth:api. There's one trap. A bearer token sent to the auth:sanctum route made Sanctum look it up in personal_access_tokens, and without that table the result was a 500 (no such table: personal_access_tokens). After I published Sanctum's migration, the same request got a clean 401.
But if you already run Passport, you probably don't need Sanctum for the SPA. Passport's CreateFreshApiToken middleware on the web group sets a laravel_token cookie that your JavaScript can use against auth:api routes. It returned 401 without an X-XSRF-TOKEN header and 200 with one. It also passed the posts:read scope check, because cookie requests carry a TransientToken that allows every scope. Sanctum does the same thing for SPA requests, where tokenCan() always returns true.
Moving from Passport to Sanctum
If you picked Passport early and only ever used personal access tokens, the switch is small. I ran these steps on the same project:
- Swap
Laravel\Passport\HasApiTokensforLaravel\Sanctum\HasApiTokensand dropimplements OAuthenticatable. - Change the
apiguard's driver frompassporttosanctum. Yourauth:apiroutes stay as they are. - Replace
CheckToken::using('posts:read')withabilities:posts:read, and register the alias. - Change
->accessTokento->plainTextTokenwherever you issue tokens. - Remove every
Passport::call and theCreateFreshApiTokenmiddleware, then runcomposer remove laravel/passport. - Drop the
oauth_*tables in a new migration and deletestorage/oauth-*.key.
After the switch, a new Sanctum token got 200 on the unchanged auth:api route, and an old Passport JWT got 401. Every existing token dies in the move, so plan for users and integrations to sign in again.
The migration for step 6:
public function up(): void
{
foreach (['oauth_auth_codes', 'oauth_access_tokens', 'oauth_refresh_tokens', 'oauth_clients', 'oauth_device_codes'] as $table) {
Schema::dropIfExists($table);
}
}
FAQ
Is Sanctum secure enough for production?
Yes, for what it's built for. Tokens are stored as SHA-256 hashes, so a database leak doesn't expose usable tokens. SPA auth is Laravel's session with CSRF protection, and no token ever lives in JavaScript. The problems I hit were all configuration: tokens that never expire by default, and a stateful domain list that doesn't match the frontend.
Does Sanctum support OAuth or "Login with Google"?
No. Sanctum has no OAuth support. "Login with Google" is your app acting as an OAuth client, which is what Laravel Socialite does. Passport is the other side, your app as the OAuth server that other apps sign in through. Plenty of apps need Socialite and never need Passport.
Are Passport tokens stateless because they're JWTs?
No. Passport checks each token's row on every request. I revoked a token and the next call got 401 straight away. You get the size of a JWT (about 1,000 characters per token) without skipping the database.
Which should a mobile app use?
Sanctum tokens, issued from a login route like the one above and kept in the iOS Keychain or Android Keystore. Name each token after the device, so a user can revoke a lost phone without signing out everywhere else.
Do I need Passport for a Laravel MCP server?
Only for MCP clients that require OAuth. The MCP docs also support Sanctum bearer tokens, and they recommend staying on Sanctum until a client you need only supports OAuth.
Which one to pick
Start with Sanctum. Its token and cookie flows covered everything I'd build for my own frontend, mobile app or API keys, with one package and one table. Fix the things the installer skips (statefulApi() and the ability aliases) and set an expiration.
Add Passport when an application you don't control needs to act for your users: a partner integration, a developer platform, an MCP client that only speaks OAuth. In those cases a consent screen, client secrets and refresh token rotation are features, not overhead. And if you do add it, define the api guard before your first request, or you'll see the same 500 I did.
About Hafiz
Senior Full Stack Developer. I build production software with Laravel, Filament, Vue, and AI integrations, and write about the real decisions behind shipping it.
Get in touch →Get web development tips via email
Join 50+ developers • No spam • Unsubscribe anytime
Related Articles
Slow Job Alerts in Laravel 13.40: What whenJobRunsLongerThan Catches and What It Misses
I ran Laravel 13.40's new slow job alerts against fast, slow, failed, released a...
Herd 2 Workspaces for Parallel Coding Agents: What Is Isolated and What Is Not
I made five Herd 2 workspaces for one Laravel app and tried to break them. The d...
One Request Waited 5 Seconds to Clean Up Laravel Sessions. Here Is What 13.39's session:garbage-collect Changes
I filled a Laravel sessions table with a million expired rows. The lottery made...