API Authentication with Laravel Sanctum

November 25, 2025
2 min read
By Nour Sallam

Table of Contents

This is a list of all the sections in this post. Click on any of them to jump to that section.

API Authentication with Laravel Sanctum

Passport is great for OAuth2, but for simple SPAs (Single Page Applications) or Mobile Apps, Laravel Sanctum is the perfect fit.

Access Tokens

Sanctum allows each user to generate multiple API tokens for their account. These tokens can have specific abilities.

$token = $user->createToken('iphone-app', ['server:update'])->plainTextToken;

SPA Authentication

If your frontend (Vue, React) and backend share the same top-level domain, Sanctum uses cookie-based session authentication. This effectively avoids the complexity of storing access tokens in local storage and dealing with XSS issues.

  1. Configure SANCTUM_STATEFUL_DOMAINS in .env.
  2. Make a request to /sanctum/csrf-cookie to initialize the CSRF protection.
  3. Login normally.

Protecting Routes

Protecting a route is as simple as adding middleware:

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

Limiting Abilities

You can check token abilities in your requests:

if ($user->tokenCan('server:update')) {
    //
}

Conclusion

Sanctum offers a perfect balance between simplicity and security for modern API development in the Laravel ecosystem.