I’m always excited to take on new projects and collaborate with innovative teams to build impactful digital solutions.
A complete deep-dive into Laravel authentication covering Sanctum, Passport, JWT, custom guards, multi-auth, and security best practices for 2026.
Authentication is the backbone of almost every web application. Laravel provides multiple authentication mechanisms, each suited to different scenarios. This deep dive explores Sanctum, Passport, JWT, and custom guards, with security best practices throughout.
Laravel's authentication is built around two core concepts: guards (how users are authenticated for each request) and providers (how users are retrieved from storage). The default configuration lives in config/auth.php.
Sanctum is the recommended solution for SPAs, mobile apps, and simple token-based APIs. It provides a featherweight authentication system.
composer require laravel/sanctum
php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
php artisan migrate
$token = $user->createToken('api-token', ['read', 'write'])->plainTextToken;
// Return this to the client. Store it securely!
Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
return $request->user();
});
if ($user->tokenCan('read')) {
// User's token has the 'read' ability
}
// Check in middleware
Route::middleware('abilities:read,write')->group(function () {
// ...
});
Passport implements full OAuth2.0 server, ideal for API-first applications that need third-party clients to authenticate.
composer require laravel/passport
php artisan passport:install
php artisan migrate
use Laravel\Passport\ClientRepository;
$client = app(ClientRepository::class)->create(
null, 'Client Name', null, '', ['read']
);
use Illuminate\Support\Facades\Http;
$response = Http::asForm()->post('https://example.com/oauth/token', [
'grant_type' => 'password',
'client_id' => 'client-id',
'client_secret' => 'client-secret',
'username' => 'user@example.com',
'password' => 'password',
'scope' => 'read',
]);
return $response->json();
For maximum flexibility, the tymon/jwt-auth package is a popular choice:
composer require tymon/jwt-auth
php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\LaravelServiceProvider"
$token = auth()->attempt($credentials);
// Add custom claims
$customClaims = ['user_id' => 1, 'role' => 'admin'];
$payload = JWTFactory::sub(1)->myCustomClaims($customClaims)->makeClaims();
$token = JWTAuth::encode($payload);
Sometimes you need to authenticate against something other than Eloquent users - like an API key table or an external service.
use Illuminate\Auth\GuardHelpers;
use Illuminate\Contracts\Auth\Guard;
use Illuminate\Contracts\Auth\UserProvider;
use Illuminate\Http\Request;
class ApiKeyGuard implements Guard
{
use GuardHelpers;
protected $request;
public function __construct(UserProvider $provider, Request $request)
{
$this->provider = $provider;
$this->request = $request;
}
public function user()
{
if (! is_null($this->user)) {
return $this->user;
}
$token = $this->request->header('X-API-KEY');
if ($token) {
$this->user = $this->provider->retrieveByCredentials([
'api_key' => $token,
]);
}
return $this->user;
}
public function validate(array $credentials = [])
{
return $this->provider->retrieveByCredentials($credentials) !== null;
}
}
// config/auth.php
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'admin' => [
'driver' => 'session',
'provider' => 'admins',
],
],
'providers' => [
'users' => ['driver' => 'eloquent', 'model' => App\Models\User::class],
'admins' => ['driver' => 'eloquent', 'model' => App\Models\Admin::class],
],
// Login as admin
if (Auth::guard('admin')->attempt($credentials)) {
return redirect()->intended('/admin/dashboard');
}
// Middleware
Route::middleware('auth:admin')->prefix('admin')->group(function () {
// Admin routes
});
Route::get('/email/verify/{id}/{hash}', function (EmailVerificationRequest $request) {
$request->fulfill();
return redirect('/home');
})->middleware(['auth', 'signed'])->name('verification.verify');
// Middleware for protected routes
Route::middleware('auth', 'verified')->group(function () {
// Routes requiring verified email
});
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Crypt;
public function enableTwoFactor(Request $request)
{
$user = $request->user();
$secret = $user->createTwoFactorSecret();
return response()->json([
'qr_code' => $secret->toQrCodeSvg(),
'recovery_codes' => $secret->recoveryCodes(),
]);
}
| Scenario | Recommendation |
|---|---|
| SPA (Vue/React) + Laravel API | Sanctum |
| Mobile App | Sanctum tokens |
| Third-party OAuth clients | Passport |
| Microservices | JWT |
| Simple admin + user | Multi-guard session auth |
| API key integrations | Custom guard |
Laravel's authentication ecosystem is remarkably complete. Start with Sanctum for most projects, graduate to Passport for OAuth needs, and use custom guards for specialized integrations. Secure your tokens, monitor auth events, and your authentication layer will be rock solid.
Your email address will not be published. Required fields are marked *