"Sanctum, Passport or JWT?" gets asked as if the three were competitors. They aren't quite. Sanctum and Passport are first-party Laravel packages. JWT is not a package at all: it's a token format (RFC 7519) that third-party Laravel packages build on. The useful question is not "which is best" but who is calling your API, and do you need OAuth2?
For most Laravel applications the answer is Sanctum, and Laravel's own documentation says so. This article explains why, shows what each option does with real output, and covers the cases where Passport or JWT is the right call. I ran Sanctum 4.4.0 in a Laravel 13.40 app and tested JWT behavior with firebase/php-jwt 7.2.1. Passport I could only check against the documentation, and I say so where it matters.
The short answer
| Sanctum | Passport | JWT (community packages) | |
|---|---|---|---|
| What it is | Lightweight first-party package: cookie auth for SPAs, plus simple API tokens | First-party full OAuth2 server | A signed token format; packages such as tymon/jwt-auth and php-open-source-saver/jwt-auth wrap it |
| Best for | Your own SPA, mobile app, or simple API tokens | Third parties logging in through your app (OAuth2), MCP servers | Stateless verification across services, if you accept the trade-offs |
| Revoking a token | Delete a row; immediate | Revoke server-side | Needs server-side state (a denylist) to revoke early |
| Setup weight | Light | Heavy (clients, keys, grants) | Medium, plus your own key and lifetime decisions |
The decision flow, in order:
- Is it a regular browser app on the same Laravel project? Use Laravel's built-in session authentication; you don't need any of these.
- Is it your own SPA or mobile app, or do you just want to hand out API tokens? Sanctum.
- Do outside developers need "Log in with your app" or standard OAuth2 flows, or will an MCP client connect? Passport.
- Do several independent services need to verify tokens without calling back to one database? Consider JWT, and plan revocation first.
Sanctum: two things in one package
The docs describe two separate problems Sanctum solves. First, API tokens: a simple way to issue tokens "without the complication of OAuth", stored in one database table and sent in the Authorization header. Second, SPA authentication, where Sanctum doesn't use tokens at all and relies on Laravel's cookie-based session authentication instead, only for requests that come from your own SPA frontend. It is fine to use only one of the two.
The setup from the docs is php artisan install:api, then the HasApiTokens trait on your user model:
// app/Models/User.php
use Laravel\Sanctum\HasApiTokens;
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;
}
Protect routes with the sanctum guard. The abilities check needs its middleware alias registered once in bootstrap/app.php:
// bootstrap/app.php, inside withMiddleware()
$middleware->alias([
'abilities' => \Laravel\Sanctum\Http\Middleware\CheckAbilities::class,
'ability' => \Laravel\Sanctum\Http\Middleware\CheckForAnyAbility::class,
]);
// routes/api.php
Route::middleware('auth:sanctum')->get('/user', fn (Request $request) => $request->user()->only('id', 'name', 'email'));
Route::middleware(['auth:sanctum', 'abilities:orders:read'])->get('/orders', fn () => ['orders' => []]);
Route::middleware(['auth:sanctum', 'abilities:orders:write'])->post('/orders', fn () => ['created' => true]);
Route::middleware('auth:sanctum')->post('/logout', function (Request $request) {
$request->user()->currentAccessToken()->delete();
return ['ok' => true];
});
Issuing tokens is one call. This is the pattern from the docs for a mobile login endpoint, which checks the credentials and returns a token named after the device:
Route::post('/sanctum/token', function (Request $request) {
$request->validate([
'email' => 'required|email',
'password' => 'required',
'device_name' => 'required',
]);
$user = User::where('email', $request->email)->first();
if (! $user || ! Hash::check($request->password, $user->password)) {
throw ValidationException::withMessages([
'email' => ['The provided credentials are incorrect.'],
]);
}
return $user->createToken($request->device_name)->plainTextToken;
});
What Sanctum does, as tested
I created a user and three tokens: one with all abilities, one limited to orders:read, and one that expires after two seconds. This is what is stored:
full abilities=["*"] expires_at=NULL stored=b702e54970e2...
readonly abilities=["orders:read"] expires_at=NULL stored=4018077e2989...
short abilities=["*"] expires_at=2026-11-11 15:05:31 stored=921fc96a0f45...
plain-text token shown to user: 1|R1vlLbpDsiZM...
sha256(secret part) matches stored hash: true
config sanctum.expiration = NULL
Three facts are visible here. The user's token looks like 1|random, not a JWT. The database holds only a SHA-256 hash, which matches the docs, so the plain text exists only at creation time. And expires_at is NULL with sanctum.expiration unset: the docs confirm that by default Sanctum tokens never expire and can only be invalidated by revoking them. Set an expiration unless you really want that.
The requests, against a local server:
$ curl /api/user (no token)
{"message":"Unauthenticated."} [401]
$ curl /api/user (full token)
{"id":1,"name":"Ann","email":"ann@example.test"} [200]
$ GET /api/orders (readonly token, needs orders:read)
{"orders":[]} [200]
$ POST /api/orders (readonly token, needs orders:write)
{"message":"Invalid ability provided."} [403]
$ POST /api/orders (full token)
{"created":true} [200]
(With debug mode on, the 403 response also carries a stack trace; I show only the message.) Revocation takes effect on the very next request, because the token's row is gone:
$ POST /api/logout (full token)
{"ok":true} [200]
$ GET /api/user (same token again)
{"message":"Unauthenticated."} [401]
$ GET /api/user (short token, 2s lifetime, age ~3s)
{"message":"Unauthenticated."} [401]
Set a global lifetime in config/sanctum.php ('expiration' is in minutes) or per token, as the docs show: createToken('name', ['*'], now()->plus(weeks: 1)). Add the documented sanctum:prune-expired --hours=24 command to your scheduler so old rows don't pile up.
For a first-party SPA, the docs say SPA and API must share a top-level domain (subdomains are fine). You configure stateful domains, call /sanctum/csrf-cookie first, then log in. In that mode no token is stored in the browser, which removes a whole class of "where do I keep the token" questions.
Passport: when you actually need OAuth2
Passport is a full OAuth2 server. The docs put it plainly: if your application absolutely needs to support OAuth2, use Passport; to authenticate a single-page application or mobile application, or to issue API tokens, use Sanctum. The authentication page adds that most applications don't need the complexity of the OAuth2 specification, and that Passport is the choice if you're building an MCP server that AI clients will connect to, since those clients typically expect OAuth.
What you get, per the Passport documentation:
- Authorization code grant, and authorization code with PKCE for SPAs and mobile apps.
- Client credentials for machine-to-machine access, and device authorization for browserless devices.
- Scopes, refresh tokens and personal access tokens.
- The password and implicit grants are marked deprecated: "We no longer recommend" them.
Setup is heavier: php artisan install:api --passport runs migrations for OAuth clients and tokens and generates encryption keys, and you then create clients with passport:client variants. By default Passport issues long-lived access tokens that expire after one year, which you can shorten with Passport::tokensExpireIn() and related methods. I did not install Passport for this article, so none of that was run; it is all from the documentation.
If your use of Passport amounts to issuing personal access tokens to your own users, the docs themselves suggest considering Sanctum instead.
JWT: a token format, not a package choice
A JWT carries its claims inside the token and is signed, so a server can verify it without a database lookup. RFC 7519 defines the registered claims: iss (issuer), sub (subject), aud (audience), exp (expiry, after which the token must not be accepted), nbf, iat and jti (a unique ID). Laravel doesn't ship a JWT guard. The common packages are tymon/jwt-auth and its fork php-open-source-saver/jwt-auth. When I read their repositories on 11 November 2026, both allowed Laravel 13 in composer.json and had commits within the previous few weeks (Tymon's latest tag was 2.3.1; the fork's was v2.10.0 and requires PHP 8.3 or newer). That tells you they're maintained, not that they're right for you.
To see how JWTs behave without any framework, I ran the plain firebase/php-jwt library:
header alg: HS256
payload is only encoded, not encrypted: {"iss":"https://api.example.test","aud":"example-mobile-app","sub":"42","iat":N,"exp":N,"jti":"tok-001"}
1 valid token accepted, sub=42
2 payload edited Firebase\JWT\SignatureInvalidException: Signature verification failed
3 alg "none" token UnexpectedValueException: Algorithm not supported
4 wrong key Firebase\JWT\SignatureInvalidException: Signature verification failed
5 after "logout", no denylist accepted
6 same token, jti denylisted RuntimeException: token revoked (jti on denylist)
7 after exp (3s later) Firebase\JWT\ExpiredException: Expired token
(iat and exp are replaced by N because they are timestamps that change on every run.) What this shows:
- The payload is readable by anyone holding the token. It's base64-encoded, not encrypted. Never put secrets or personal data in it that the client shouldn't see.
- Tampering is caught. Editing the payload (line 2) or using the wrong key (line 4) fails signature verification.
-
The
nonealgorithm is rejected, because the caller pinned the algorithm. Passing the expected algorithm innew Key($secret, 'HS256')is what protects you. RFC 8725, the JWT best-practices document, makes this the first rule: libraries must let the caller specify the supported algorithms, and applications should not trust the token's ownalgheader. -
Logout does nothing by itself (line 5). The signature and expiry are all the server checks, so a stolen or "logged out" token is accepted until
exp. To revoke early you need server-side state, such as thejtidenylist in line 6. At that point you have given up part of the "no database lookup" advantage. - Expiry works (line 7), which is why access-token lifetimes should be short.
RFC 8725 also recommends validating the issuer and audience and using explicit typing; my $check function does the first two by hand. Whatever package you choose, confirm it validates iss, aud and exp and that your key is long and random. For a first-party app that only talks to your own Laravel backend, JWT adds complexity that Sanctum avoids.
A fair design comparison, labelled as reasoning rather than a benchmark: Sanctum looks the token up in your database on each request (that's how revocation can be immediate), while a JWT can be verified from the signature alone. For one Laravel app that difference rarely matters. It matters more when many independent services must verify tokens without sharing a database.
Which one for which situation
| Your situation | Use | Why |
|---|---|---|
| Server-rendered Laravel app | Built-in session auth | No tokens needed |
| Your own SPA on the same top-level domain | Sanctum (cookie mode) | No token stored in the browser |
| Your own mobile app | Sanctum tokens | Simple, revocable per device, with abilities |
| Public API where customers generate their own keys | Sanctum tokens | Hashed storage, abilities, easy revocation |
| "Log in with our app" for third-party developers | Passport | That is what OAuth2 is for |
| Server-to-server access with client credentials | Passport | Standard grant for machine access |
| MCP server for AI clients | Passport | The Laravel docs recommend it; MCP clients typically expect OAuth |
| Many separate services must verify tokens independently | JWT, or an external identity provider | Stateless verification; plan revocation and key rotation |
Common mistakes
- Installing Passport for a first-party mobile app. You pay for OAuth2 you don't use. The docs steer you to Sanctum.
-
Leaving Sanctum tokens non-expiring. It's the default. Set
sanctum.expirationor a per-token expiry and prune old rows. - Using tokens for a same-domain SPA. Sanctum's cookie mode exists so the browser doesn't hold a bearer token.
-
Granting
['*']to every token. Give tokens the abilities they need; you saw a limited token get a 403. - Long-lived JWTs with no revocation plan. Keep access tokens short and decide how you'd cut off a stolen one.
-
Trusting the
algheader. Pin the algorithm on verification. - Putting sensitive data in a JWT payload. Signed is not secret.
- Treating password and implicit grants as current. Passport's docs call them deprecated.
Alternatives
Built-in session authentication covers a monolithic app. The Laravel docs also note that the cookie-based libraries and the token packages aren't mutually exclusive, so an app can serve a web UI and an API at once. If your organization already runs an identity provider (Keycloak, Auth0, or similar), validating its JWTs in Laravel can be the better design than building your own issuer; I haven't evaluated those products here.
Related Dev Talk articles
- 10 Common API Design Mistakes Developers Make
- Laravel .env Configuration: env() vs config() Explained
- Laravel Scheduler Not Running: Cron and schedule:run Fixes
Frequently asked questions
Is Sanctum a JWT implementation?
No. In the test, the token looked like 1|random-string, and the database stored only its SHA-256 hash. Authentication is a lookup, not a signature check.
Can I revoke a JWT?
Not by itself. You need server-side state, such as a denylist of token IDs, or very short lifetimes with refresh tokens. Both packages mentioned above have a token blacklist in their source (a TokenBlacklistedException and blacklist handling in JWT.php); check their docs for how entries are stored and for how long.
Do Sanctum tokens expire?
Only if you configure it. The default is no expiry. Use sanctum.expiration (minutes) for a global limit or pass an expiry date to createToken.
Can I use Sanctum and Passport in the same app?
The Laravel docs say the cookie-based authentication and the token packages are not mutually exclusive. I did not test running both packages together, and most apps only need one.
What about refresh tokens?
Passport issues refresh tokens as part of OAuth2. Sanctum's documentation doesn't describe refresh tokens: you issue a new token or let the user log in again. Both JWT packages I read have a refresh() method in their source; check how the one you choose handles it.
Sources
- Laravel documentation: Sanctum
- Laravel documentation: Passport
- Laravel documentation: Authentication
- RFC 7519: JSON Web Token (JWT)
- RFC 8725: JSON Web Token Best Current Practices
- laravel/sanctum on GitHub, firebase/php-jwt on GitHub
Originally published on DEV Talk.
Top comments (0)