Use Laravel Sanctum for SPA and Mobile Authentication
Summary: Authenticate Vue or Flutter apps using Laravel Sanctum.
Modern web and mobile applications demand seamless, secure authentication systems. Laravel Sanctum is the perfect lightweight solution for apps requiring simple token-based authentication, especially Single Page Applications (SPAs) crafted in Vue.js and mobile applications built in Flutter.
In this article, we explore how Sanctum bridges the authentication gap between Laravel backends and SPA or mobile frontends. We'll cover installing Sanctum, configuring it for SPAs and mobile apps, and demonstrate token-based authentication for both Vue.js and Flutter clients.
What is Laravel Sanctum?
Laravel Sanctum provides a featherweight authentication system for SPAs (using cookies) as well as simple API token usage for mobile apps. Unlike Laravel Passport—which is more tailored for OAuth2 flows—Sanctum makes it easy to authenticate with minimal setup and complexity.
Key features:
- Cookie-based session authentication for SPAs.
- API token authentication for mobile or external clients.
- Simplicity in configuration and use.
Installing Laravel Sanctum
Let's get started by installing Sanctum in your Laravel project.
composer require laravel/sanctum
Publish the Sanctum configuration and migration files:
php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
php artisan migrate
Add Sanctum's middleware to your api
middleware group in app/Http/Kernel.php
:
'api' => [
\Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
'throttle:api',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
Note: For SPAs (like those built with Vue.js), cookie-based authentication requires correctly setting your
SESSION_DOMAIN
andSANCTUM_STATEFUL_DOMAINS
in.env
.
Authentication for SPAs (e.g., Vue.js)
Sanctum allows SPAs on the same domain (or subdomains) to use Laravel's session-based authentication, leveraging Laravel's built-in features like CSRF protection.
1. Backend Configuration
Set Statefulness:
SANCTUM_STATEFUL_DOMAINS=localhost,127.0.0.1,your-app.test
SESSION_DOMAIN=.your-app.test
CSRF Protection:
Ensure your SPA makes an initial request to /sanctum/csrf-cookie
to get a CSRF token before making authentication requests.
2. Example SPA Login Flow
A. Vue.js Login Request
// axios instance setup with credentials
import axios from 'axios';
axios.defaults.withCredentials = true; // Important for cookies!
// Get CSRF cookie
await axios.get('http://your-backend.test/sanctum/csrf-cookie');
// Then, login
const response = await axios.post('http://your-backend.test/login', {
email: form.email,
password: form.password,
});
B. Sticky Session
Once logged in, all subsequent requests will automatically be authenticated via the session cookie.
C. Protecting API Routes
In Laravel, protect your API routes with the auth:sanctum
middleware:
Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
return $request->user();
});
Authentication for Mobile Apps (e.g., Flutter)
Unlike browser-based SPAs, mobile clients typically authenticate using API tokens. Sanctum lets users generate tokens to authenticate subsequent requests.
1. Issuing API Tokens
After authenticating (e.g., via email and password), issue a token for the user:
// In your LoginController
public function login(Request $request)
{
$request->validate([
'email' => 'required|email',
'password' => 'required',
]);
$user = User::where('email', $request->email)->first();
if (! $user || ! Hash::check($request->password, $user->password)) {
return response()->json(['message' => 'Invalid credentials'], 401);
}
// Issue token
$token = $user->createToken('mobile-app')->plainTextToken;
return response()->json(['token' => $token, 'user' => $user]);
}
2. Flutter API Call Example
// Example using the http package
import 'package:http/http.dart' as http;
// Login and retrieve token
final response = await http.post(
Uri.parse('http://your-backend.test/api/login'),
body: {'email': email, 'password': password},
);
// Parse and store token
final token = jsonDecode(response.body)['token'];
// Use token in headers for authenticated requests
final userResponse = await http.get(
Uri.parse('http://your-backend.test/api/user'),
headers: {'Authorization': 'Bearer $token'},
);
3. Protecting API Routes
Again, use Sanctum middleware in your API routes:
Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
return $request->user();
});
Expiring & Revoking Tokens
Tokens can be explicitly revoked:
$user->tokens()->delete(); // Revokes all tokens
Or selectively delete tokens for logouts or device deauthorization.
Recap
- Use Sanctum for SPA authentication (cookie/session-based) and mobile apps (API tokens).
- For Vue.js, ensure CSRF and proper cookie domains are configured.
- For mobile, issue API tokens after credential verification and use them as Bearer tokens in requests.
- Sanctum is simple to configure and secures both SPA and mobile app authentication needs.
Further Reading
Start building secure, authenticated mobile and SPA applications with Laravel Sanctum today!