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.
- Configure
SANCTUM_STATEFUL_DOMAINSin.env. - Make a request to
/sanctum/csrf-cookieto initialize the CSRF protection. - 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.
