Laravel Daily's

Lightweight API Authentication with Laravel Sanctum

hero image

Authentication doesn't have to be a headache. For years, developers reached for complex OAuth2 servers like Laravel Passport just to handle a simple mobile app. It worked, but it was often overkill. You spent more time configuring scopes and secrets than shipping features.

Then came Sanctum. Originally called Airlock, it carved out a new space in the ecosystem. It provides a featherweight authentication system for SPAs, mobile apps, and simple token-based APIs. It’s built for the way most of us actually build apps today.

You don't need a heavy infrastructure for first-party applications. You need something that gets out of the way. Sanctum is that tool.

The Dual Nature of Sanctum

Sanctum is unique because it handles two distinct problems with one package. It isn't just one type of auth; it's a bridge between two worlds.

First, it handles Single Page Application (SPA) authentication. This uses traditional session cookies, just like a standard web app. It’s perfect for React, Vue, or Svelte frontends that live on the same domain as your API.

Second, it handles API tokens. These are personal access tokens that clients send in a header. They are the standard choice for mobile apps, CLI tools, and third-party integrations.

By covering both, Sanctum lets you build one backend that serves every client. You don't have to maintain separate auth logic for your web dashboard and your iOS app.

SPA Authentication: The Cookie Choice

When you're building a dashboard in Vue or React, you might be tempted to use tokens. It’s the "modern" way, right? Not necessarily. For first-party SPAs, cookies are often the superior choice.

A bright, cartoony illustration of a secure cookie jar with a lock, representing SPA authentication security

Sanctum’s SPA mode leverages Laravel’s built-in session authentication. It uses the web guard under the hood. When your frontend makes a request, Laravel treats it like any other web request. It boots the session and checks the cookie.

Why Cookies Matter for Security

Security is about closing gaps. If you store an API token in localStorage, it’s vulnerable. Any cross-site scripting (XSS) attack can reach in and grab that token. Once a thief has it, they have full access until the token expires.

Cookies are different. Sanctum uses http-only cookies. JavaScript cannot read these cookies. Even if an attacker finds a way to execute script on your page, they can't steal the session. This single choice significantly raises the security floor of your application.

The CSRF Protection Flow

Sanctum also brings Laravel’s robust CSRF protection to your API. Before your SPA logs in, it hits a special /sanctum/csrf-cookie endpoint. This sets the CSRF token. Every subsequent request sends this token back.

This prevents other sites from tricking your users into performing actions. It’s the same gold-standard security we’ve used for years, adapted for the AJAX era. It’s elegant, simple, and effective.

Mobile and Third-Party: The Token Path

Sometimes, cookies won't work. Mobile apps don't handle cookies the same way browsers do. Third-party services or CLI scripts definitely don't. This is where Sanctum's API tokens shine.

A cartoony smartphone displaying a golden digital token with wings, symbolizing mobile API authentication

Each user in your system can have multiple tokens. You might have one for "iPhone," one for "MacBook," and one for "GitHub Action." Sanctum stores these in a simple personal_access_tokens table.

Fine-Grained Control with Abilities

Tokens shouldn't always have total power. Maybe your mobile app only needs to read data, not delete it. Sanctum handles this through "abilities."

When you create a token, you can assign it specific permissions:

$user->createToken('mobile-app', ['orders:read', 'orders:place']);

Inside your routes or controllers, you can check these abilities easily. It’s a lightweight way to implement permissions without needing a full-blown role-based access control (RBAC) system. It keeps your code clean and your logic straightforward.

Simple Integration: The Developer Experience

Laravel is known for its joyful development experience. Sanctum fits this philosophy perfectly. You don't need to be a security expert to set it up.

Starting Small

Integration begins with a trait. You add HasApiTokens to your User model. This gives you the methods to create and manage tokens. Then, you add a piece of middleware to your api group in app/Http/Kernel.php.

The EnsureFrontendRequestsAreStateful middleware is where the magic happens. It detects if a request is coming from your SPA. If it is, it boots the session. If not, it falls back to token authentication. It’s a "set it and forget it" solution.

Unified Guard

You protect your routes using the auth:sanctum guard. It doesn't matter if the request is from a cookie-based SPA or a token-based mobile app. The guard handles both seamlessly.

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

This unification is a massive productivity boost. You write your business logic once. You test your routes once. The infrastructure handles the variations in how clients identify themselves.

Comparing the Approaches

Choosing between cookies and tokens depends on your client. Beginners often struggle with this choice, but the rule is simple: use cookies where you can, and tokens where you must.

Aspect SPA (Cookie) Mode API Token Mode
Primary Client First-party Browser Apps Mobile, CLI, Third-party
Storage HTTP-Only Cookies App Storage / Keychain
XSS Protection Strong (JS can't read cookies) Vulnerable if in LocalStorage
CSRF Protection Automatic / Required Not required for tokens
State Stateful (Sessions) Stateless

By offering both, Sanctum ensures you aren't forced into a one-size-fits-all architecture. You can use Laravel Breeze to scaffold your entire auth flow in minutes, and it will use Sanctum by default.

Deployment and Scale

As your app grows, Sanctum grows with you. Because it relies on standard database tables and session drivers, it scales as well as Laravel does.

If you're using Laravel Forge for server management or eyeing Laravel Cloud for managed infrastructure, Sanctum fits right in. It doesn't require specialized "Auth-as-a-Service" providers. You own your data. You own your security.

Vibrant illustration of a fast-moving rocket with the Laravel logo, representing rapid shipping and deployment

Conclusion: Focus on Shipping

The goal of the Laravel ecosystem is to prevent you from reinventing the wheel. Authentication is a solved problem. Sanctum is the elegant, lightweight answer for the modern web.

It bridges the gap between traditional session-based apps and the new world of decoupled frontends. It prioritizes security without sacrificing the developer experience.

Whether you're building a side project or a massive SaaS, Sanctum provides the foundation you need. It allows you to stop worrying about the "how" of authentication and focus on the "what" of your features.

We’d love to hear how you’re using Sanctum in your latest projects. Every corner of the community is building something unique, and Sanctum is there to keep it secure. Your story belongs here.

Previous
Docker Made Simple: Getting Started with Laravel Sail
Next
Social Login Without the Headache Using Laravel Socialite