I’m always excited to take on new projects and collaborate with innovative teams to build impactful digital solutions.

Social Links

Laravel Authentication Deep Dive: Sanctum, Passport, JWT & Custom Guards Explained

A complete deep-dive into Laravel authentication covering Sanctum, Passport, JWT, custom guards, multi-auth, and security best practices for 2026.

Introduction

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.

Understanding Laravel's Auth System

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.

1. Laravel Sanctum

Sanctum is the recommended solution for SPAs, mobile apps, and simple token-based APIs. It provides a featherweight authentication system.

Installation

composer require laravel/sanctum
php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
php artisan migrate

Issuing API Tokens

$token = $user->createToken('api-token', ['read', 'write'])->plainTextToken;

// Return this to the client. Store it securely!

Protecting Routes

Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
    return $request->user();
});

Token Abilities

if ($user->tokenCan('read')) {
    // User's token has the 'read' ability
}

// Check in middleware
Route::middleware('abilities:read,write')->group(function () {
    // ...
});

2. Laravel Passport

Passport implements full OAuth2.0 server, ideal for API-first applications that need third-party clients to authenticate.

Installation

composer require laravel/passport
php artisan passport:install
php artisan migrate

Client Credentials Grant

use Laravel\Passport\ClientRepository;

$client = app(ClientRepository::class)->create(
    null, 'Client Name', null, '', ['read']
);

Password Grant Tokens

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();

3. JWT Authentication

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"

Generating Tokens

$token = auth()->attempt($credentials);

// Add custom claims
$customClaims = ['user_id' => 1, 'role' => 'admin'];
$payload = JWTFactory::sub(1)->myCustomClaims($customClaims)->makeClaims();
$token = JWTAuth::encode($payload);

4. Custom Guards

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;
    }
}

5. Multi-Authentication (Admin + User)

// 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
});

6. Email Verification

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
});

7. Two-Factor Authentication

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(),
    ]);
}

Security Best Practices

  • Always use HTTPS - tokens are transmitted over the wire
  • Hash passwords with bcrypt or argon2id (Laravel default)
  • Rate limit login attempts to prevent brute force
  • Short token lifetimes with refresh mechanisms
  • Invalidate tokens on password change
  • Log authentication events for audit trails
  • Use signed URLs for verification links

Choosing the Right Solution

ScenarioRecommendation
SPA (Vue/React) + Laravel APISanctum
Mobile AppSanctum tokens
Third-party OAuth clientsPassport
MicroservicesJWT
Simple admin + userMulti-guard session auth
API key integrationsCustom guard

Conclusion

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.

4 min read
Aug 08, 2026
By Developer Shadin
Share

Leave a comment

Your email address will not be published. Required fields are marked *