Why Sanctum is the best fit for SPA authentication.
Authentication and authorization are crucial aspects of software development, today we will see how Sanctum is the best suit for SPA(Single Page Application) and mobile API authentication and authorization. Laravel has two major packages that are Laravel Passport and Laravel Sanctum depending on the use case you can choose one of them, but when it's about SPA and you don't have any need for the OAuth2 going with Sanctum will be the best, we will discuss why and how?
Laravel Sanctum primarily solves two problems
composer require laravel/sanctum
php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
php artisan migrate
领英推荐
'api' => [
\Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
\Illuminate\Routing\Middleware\ThrottleRequests::class.':api',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
'paths' => ['api/*', 'sanctum/csrf-cookie', 'login', 'logout'],
'allowed_methods' => ['*'],
'allowed_origins' => [env('SPA_URL')], // your SPA URL
'allowed_origins_patterns' => [],
'allowed_headers' => ['*'],
'exposed_headers' => [],
'max_age' => 0,
'supports_credentials' => true,
use App\Http\Controllers\API\AuthController;
use App\Http\Controllers\API\YourController;
Route::prefix('auth')->group(function () {
Route::post('/login', [AuthController::class, 'login']);
Route::post('/register', [AuthController::class, 'register']);
Route::middleware('auth:sanctum')->post('/logout', [AuthController::class, 'logout']);
});
Route::middleware('auth:sanctum')->group(function () {
Route::get('/user', [AuthController::class, 'user']);
});
axios.defaults.withCredentials = true;
async function login(email, password) {
try {
await axios.get('/sanctum/csrf-cookie');
await axios.post('/api/auth/login', {
email: email,
password: password
});
} catch (error) {
}
}
async function logout() {
try {
await axios.post('/api/auth/logout');
} catch (error) {
}
}
Conclusion Laravel Sanctum emerges as the top choice for Single Page Applications (SPAs) seeking secure and streamlined authentication solutions. Unlike its counterpart Laravel Passport, Sanctum simplifies the complex process of API token management and offers effortless SPA authentication. By storing access tokens securely and employing cookie-based authentication, Sanctum ensures robust security measures, including CSRF protection and defense against cross-site scripting attacks. Its seamless integration capabilities make it a preferred option for developers, allowing them to focus on building user-friendly, secure SPAs without the complexities of intricate authentication systems. Sanctum’s simplicity, enhanced security, and seamless integration make it the go-to solution for modern SPAs in the ever-evolving landscape of web development.