Skip to content
Tutorials Center
My learning

Topics

Lesson 34 of 67 ยท Authentication and Authorization

API Authentication with Sanctum

Secure your Laravel API with Sanctum: personal access tokens, abilities, expiring and revoking tokens, cookie authentication for SPAs, and when to choose Passport.

A browser can log in with a session cookie, but a mobile app, a command-line tool or another server can't (or shouldn't). They send a token with every request instead: a long secret string in the Authorization header that stands in for a username and password. Laravel Sanctum is the official, lightweight package for that job. It also handles a second case: a single-page application on your own domain that authenticates with ordinary session cookies.

This lesson shows both modes, explains how tokens are issued, checked, limited and revoked, and rebuilds the token mechanics in plain PHP so nothing about them is magic. It continues from Authentication Overview and Starter Kits, where a token guard was just a different way to recognize a request. You'll build real endpoints later in Building JSON APIs with API Resources.

Installing Sanctum

In a new Laravel application, one Artisan command prepares API support, including Sanctum:

Terminal
php artisan install:api

It installs the package, creates routes/api.php and publishes the migration for the personal_access_tokens table. After php artisan migrate, add the HasApiTokens trait to your user model:

PHP
use Laravel\Sanctum\HasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;
}

Routes in routes/api.php are served under the /api prefix and don't use sessions, which is what an API client expects. To protect a route, use the auth:sanctum middleware; it means "use the guard named sanctum":

PHP
Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
    return $request->user();
});

Personal access tokens

A personal access token belongs to one user and is created on demand. The typical flow is: the client sends credentials to a login endpoint, the server verifies them and returns a token, and the client stores it and attaches it to every later request.

PHP
Route::post('/tokens', function (Request $request) {
    $request->validate([
        'email' => ['required', 'email'],
        'password' => ['required'],
        'device_name' => ['required', 'string'],
    ]);

    $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 ['token' => $user->createToken($request->device_name)->plainTextToken];
});

The client then calls the API with the header Authorization: Bearer 1|abc.... A few facts to remember:

  • The plain-text token is shown once, right after creation. Sanctum stores only a SHA-256 hash of it in the personal_access_tokens table, so a leaked database does not leak working tokens.
  • The token you see looks like an id, a pipe character and a long random string. The id lets Sanctum find the row quickly; the secret part is then compared with the stored hash.
  • The name you pass (device_name here) is just a label so users can recognize "Ana's phone" in a list of tokens.
  • Tokens are credentials. Send them only over HTTPS, and never put them in a URL.

Abilities

By default a token can do everything the user can. Abilities (older docs call them scopes) restrict that. You list them when creating the token and check them in your code:

PHP
$token = $user->createToken('report-bot', ['reports:read', 'reports:export']);

// In a controller or route:
if ($request->user()->tokenCan('reports:export')) {
    // ...
}

if ($request->user()->tokenCant('reports:delete')) {
    abort(403);
}

There is also middleware to guard entire routes: abilities:reports:read,reports:export requires all the listed abilities and ability:reports:read,reports:export requires any of them. Register their aliases in bootstrap/app.php if your project does not already map them; Sanctum's documentation shows the exact lines for your version.

The idea is least privilege: a script that only reads reports gets a token that can only read reports, so a leak is much less damaging. Abilities limit what a token may do; what the user may do is still decided by authorization (Gates and Policies), and both must allow an action.

flowchart LR
    C["API client<br/>Authorization: Bearer 7|secret"] --> M["auth:sanctum<br/>middleware"]
    M --> L["Find token row by id 7<br/>compare hash of secret"]
    L -->|"no match, expired"| X["401 Unauthorized"]
    L --> A["abilities middleware<br/>or tokenCan()"]
    A -->|"missing ability"| Y["403 Forbidden"]
    A --> H["Controller<br/>(user and policies)"]

A token request passes authentication, then the token's abilities, then your usual authorization.

Issuing and checking tokens, runnable

Here is the whole life of a token in plain PHP with an in-memory SQLite database. It follows Sanctum's design: the client gets id|secret, the table keeps only hash('sha256', secret), and lookup is by id followed by a constant-time comparison. The secret is derived from a counter so the output stays reproducible; real tokens come from random_bytes.

PHP Token issuing with a hashed lookup

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

A correct token resolves to user 7, and the failed lookups all return null (which becomes a 401 response in Laravel). The database row proves the point of hashing: even with full read access to the table, an attacker only sees a digest and cannot build the id|secret string a client sends.

Expiring and revoking tokens

By default Sanctum tokens never expire. You can set a lifetime in minutes in config/sanctum.php:

PHP
'expiration' => 60 * 24 * 30,   // 30 days; null means never

You can also give one token its own deadline when you create it (createToken($name, ['*'], now()->addWeek())). An expired token is rejected at lookup, and the scheduler can delete the dead rows with php artisan sanctum:prune-expired --hours=24; see Task Scheduling.

Revoking is just deleting rows:

PHP
$request->user()->currentAccessToken()->delete();   // log out this device
$request->user()->tokens()->where('id', $tokenId)->delete();   // one specific token
$request->user()->tokens()->delete();   // sign out everywhere

Offer users a "devices" page that lists their tokens (name, last used) and a revoke button; it is a cheap, effective security feature, and last_used_at makes it meaningful. The stand-in below adds abilities, expiry and revocation on top of the same idea, with a fake clock for repeatable output.

PHP Abilities, expiry and revocation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The three status codes tell the whole story: 401 means "I don't know who you are" (missing, unknown, expired or revoked token), 403 means "I know who you are, and the answer is no" (missing ability). Keep that difference in your APIs, since clients react to them differently.

SPA authentication with cookies

If your front end is a single-page application on the same top-level domain as your API (for example app.example.com and api.example.com), skip tokens. Tokens stored in JavaScript are exposed to any script that runs on the page, so Sanctum offers a safer path: cookie-based session authentication.

The flow in brief:

  1. The SPA requests GET /sanctum/csrf-cookie, which sets an XSRF-TOKEN cookie.
  2. The SPA posts the login form to your normal login route, sending the XSRF token in an X-XSRF-TOKEN header (libraries like Axios do this automatically when you enable credentials).
  3. Laravel logs the user in with a normal session, and the browser keeps the session cookie.
  4. Later requests carry the cookie; the auth:sanctum guard recognizes the session.

Setting it up means listing the SPA's domains as stateful so the API middleware starts a session for them, usually with $middleware->statefulApi() in bootstrap/app.php and the SANCTUM_STATEFUL_DOMAINS environment variable. You also configure CORS and cookie domains correctly. The security benefit is large: the credential is an HttpOnly cookie that JavaScript can't read, and Laravel's CSRF protection applies as usual.

Use this mode for a first-party SPA. Use tokens for mobile apps, scripts and third-party integrations. The same auth:sanctum middleware accepts both.

Sanctum or Passport?

Question Sanctum Passport
Complexity Small, one table Full OAuth2 server, keys and several tables
Typical user Your own SPA, mobile app, scripts Third parties who sign in with your accounts
Flows Personal tokens, SPA cookies Authorization code, client credentials, refresh tokens and more
Choose when You control the clients You need OAuth2 as a product feature

If you are unsure, start with Sanctum. You can add Passport later if you ever need to let other companies build apps on top of yours. For background on the standards, see JWT and OAuth.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. How does Sanctum store a personal access token?

    Only a hash is stored in personal_access_tokens, so a database leak does not expose working tokens. The plain-text value is returned once.
  2. 2. A token created with the ability ['reports:read'] is used to delete a report. Which response is correct?

    The token is valid (so the user is known), but it lacks the required ability. That is a 403. A 401 is for missing, invalid, expired or revoked tokens.
  3. 3. Which approach does Sanctum recommend for a first-party single-page app on the same top-level domain?

    Cookie-based authentication keeps the credential in an HttpOnly cookie that JavaScript cannot read and keeps CSRF protection in place.
  4. 4. How do you sign a user out of every device that holds a Sanctum token?

    Tokens are database rows, so deleting the user's tokens revokes them all. Auth::logout() affects only the session guard.
  5. 5. When is Passport a better choice than Sanctum?

    Passport is a complete OAuth2 server. If you control all clients, Sanctum is simpler.

Summary

  • Sanctum has two modes: personal access tokens (mobile apps, scripts) and cookie sessions for a first-party SPA. Both work behind auth:sanctum.
  • Run php artisan install:api, add HasApiTokens and call $user->createToken($name, $abilities); the plain-text token (id|secret) is shown once.
  • Only a SHA-256 hash is stored, so lookups go by id and a constant-time hash comparison.
  • Abilities limit a token (tokenCan(), abilities and ability middleware); authorization still applies on top.
  • Set an expiration, prune with sanctum:prune-expired and revoke by deleting token rows.
  • 401 = not authenticated, 403 = authenticated but not allowed. Choose Passport only when you need a real OAuth2 server.

Next: Gates and Policies