Intermediate LevelLaravel
How does Laravel Sanctum issue API Tokens and handle SPA session auth?
❓ Interview Prompt: Explain Laravel Sanctum, HasApiTokens trait, issuing scoped bearer tokens (createToken()), and stateful cookie SPA authentication.
Laravel Sanctum provides a lightweight authentication system for SPAs, mobile apps, and simple token APIs:
1. Mobile / Third-Party API Tokens:
Issues scoped Bearer tokens via '$user->createToken("mobile-app", ["posts:create"])->plainTextToken'.
2. SPA Cookie Authentication:
Uses stateful HTTP-only session cookies for single-page applications (Vue/React) by requesting '/sanctum/csrf-cookie' before login.
Code Implementation Example
php
<?php
use AppModelsUser;
use IlluminateHttpRequest;
use IlluminateSupportFacadesHash;
public function issueToken(Request $request)
{
$user = User::where('email', $request->email)->first();
if (! $user || ! Hash::check($request->password, $user->password)) {
return response()->json(['message' => 'Invalid credentials'], 401);
}
$token = $user->createToken('api-token', ['read', 'write'])->plainTextToken;
return response()->json(['token' => $token]);
}💡Issuing scoped API bearer token using Laravel Sanctum.
🎯 Interview Key Takeaway
Use Laravel Sanctum for lightweight API bearer token generation and stateful cookie SPA authentication.
#Sanctum#API Tokens#Authentication#Intermediate
Back to all Laravel Questions→