Skip to main content
โ† Back to Blog

How to Set Up Laravel API Authentication with Sanctum (2025 Guide)

How to Set Up Laravel API Authentication with Sanctum (2025 Guide) โ€“ cover image

Learn how to set up Laravel Sanctum for secure API authentication in 2025. This guide will help you protect your RESTful endpoints using token-based authentication — ideal for SPAs and mobile apps.


๐Ÿ” What Is Laravel Sanctum?

Laravel Sanctum is a simple package for API token authentication. It's perfect for single-page apps, mobile apps, or any frontend consuming your Laravel API.

๐Ÿš€ Why Use Sanctum for API Auth?

  • Lightweight and easy to set up
  • Works seamlessly with SPAs (Vue/React)
  • Perfect for mobile APIs
  • No need for OAuth complexity
  • Secure and well-integrated with Laravel

โš™๏ธ Step 1: Install Laravel Sanctum

composer require laravel/sanctum

Publish Sanctum’s config and migration files:

php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
php artisan migrate

๐Ÿ”ง Step 2: Configure Middleware

In app/Http/Kernel.php, update the api middleware group:

'api' => [
    \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
    'throttle:api',
    \Illuminate\Routing\Middleware\SubstituteBindings::class,
],

๐Ÿงช Step 3: Set Up Auth Scaffolding

You can use Laravel Breeze to set up API authentication logic:

composer require laravel/breeze --dev
php artisan breeze:install api
php artisan migrate

๐Ÿ”‘ Step 4: Issue Tokens

In your login controller, issue a token on successful login:

$user = User::where('email', $request->email)->first();

if (! $user || ! Hash::check($request->password, $user->password)) {
    return response()->json(['error' => 'Invalid credentials'], 401);
}

return $user->createToken('auth_token')->plainTextToken;

Use the token in your API headers like this:

Authorization: Bearer {token}

๐Ÿ”’ Step 5: Protect Routes

In routes/api.php:

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

๐Ÿงผ Revoking Tokens

To revoke all of a user's tokens:

$user->tokens()->delete();

๐Ÿงช Testing Your API Auth

  • Register a user
  • Log in and grab the token
  • Call protected routes with the token

โœ… Final Tips for Sanctum

  • Use HTTPS in production for security
  • Use Laravel Horizon to monitor token usage
  • Sanctum is ideal for SPAs and mobile apps
  • For OAuth or third-party access, use Laravel Passport instead

๐Ÿ‘จ‍๐Ÿ’ป Ready to Secure Your API?

Laravel Sanctum is the simplest and most efficient way to add API authentication to your Laravel app in 2025. Whether you're building a SPA, mobile app, or custom API dashboard, Sanctum gives you the tools to stay secure and scalable.

Need help setting up Laravel authentication?
Contact me here →