Building Secure APIs with Laravel Sanctum

Building Secure APIs with Laravel Sanctum

May 19, 2025
2 min read
333views
Table of Contents

Introduction

APIs power modern web and mobile applications, but they also open up new attack surfaces. Laravel Sanctum provides a lightweight, first-party solution for authenticating Single Page Applications (SPAs), mobile apps, and simple token-based APIs. In this post, you’ll learn how to:

  1. Install and configure Sanctum

  2. Protect your API routes

  3. Issue and revoke tokens

  4. Secure both SPAs and mobile clients

  5. Write tests to verify your setup

Let’s dive in!


1. Install & Publish Sanctum

  1. Require the package via Composer:

    
    composer require laravel/sanctum 
  2. Publish the configuration and migration:

    php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider" 
  3. Run the migrations to create the personal_access_tokens table:

    php artisan migrate 

2. Configuration

In config/sanctum.php, you’ll find:

  • stateful domains (for SPA authentication)

  • expiration of issued tokens

  • middleware applied to your API routes

By default Sanctum uses your application’s api guard. You can customize guards in config/auth.php if needed.


3. Protecting Routes

In routes/api.php, wrap any routes you want protected with the auth:sanctum middleware:

use Illuminate\Http\Request; use Illuminate\Support\Facades\Route;  Route::middleware('auth:sanctum')->group(function () {     Route::get('/user', function (Request $request) {         return $request->user();     });      Route::post('/posts', [PostController::class, 'store']);     // …more protected endpoints… }); 

Anyone calling these endpoints must include a valid token in their Authorization header.


4. Issuing & Revoking Tokens

4.1 Personal Access Tokens

From any authenticated user, you can create a token like this:

$user = Auth::user();  // Create a token with optional abilities (scopes) $token = $user->createToken('mobile-token', ['create', 'update'])->plainTextToken;  return response()->json([     'access_token' => $token,     'token_type'   => 'Bearer', ]); 

To revoke all of a user’s tokens:

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

Or revoke a single token by ID:

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

5. Authenticating SPAs

Sanctum uses Laravel’s session cookies to authenticate SPAs. In config/sanctum.php, add your frontend domain to the stateful array:

'stateful' => explode(',', env('SANCTUM_STATEFUL_DOMAINS', 'localhost:3000,myapp.test')), 

Then, from your SPA (e.g. React/Vue), first hit the /sanctum/csrf-cookie endpoint, and subsequent calls to /login or any auth:sanctum routes will use the session cookie automatically.


6. Authenticating Mobile & Third-Party Clients

Mobile apps and third-party services can’t use cookies; instead, they’ll use the tokens you issued. Include in your requests:

Authorization: Bearer YOUR_PERSONAL_ACCESS_TOKEN 

Sanctum will validate the token and check any abilities you defined.


7. Testing Your Setup

  1. Feature Test Example

    public function test_can_access_protected_route() {     $user = User::factory()->create();     $token = $user->createToken('test-token')->plainTextToken;      $response = $this->withHeaders([         'Authorization' => 'Bearer ' . $token,     ])->getJson('/api/user');      $response->assertStatus(200)              ->assertJson(['id' => $user->id]); } 
  2. Token Revocation
    Verify that after deleting a token, requests fail with a 401 Unauthorized.


Conclusion

Laravel Sanctum makes it easy to secure your APIs with both session-based SPA authentication and token-based access for mobile or third-party clients. By following the steps above—installing Sanctum, protecting routes, issuing tokens, and writing tests—you’ll have a robust authentication layer in minutes.

Happy coding! 🚀

Rate this article

Share this article

Related Articles

Smart Home Technology: Gadgets to Simplify Your Life

Smart Home Technology: Gadgets to Simplify Your Life

Discover how smart home technology simplifies daily tasks with innovative devices—from voice-controlled smart speakers and energy-saving thermostats to automated lighting and security systems. Upgrade...
848
1
0
Top 10 New Trending Technologies To Learn in 2025

Top 10 New Trending Technologies To Learn in 2025

Explore the top trending technologies to learn in 2025, from Generative AI to Cybersecurity, Blockchain, Cloud Computing, and more. Stay ahead in the tech industry and unlock high-paying opportunities...
473
1
0
From Code to Couture: How Next.js Optimization Impacts AI-Driven Fashion Design

From Code to Couture: How Next.js Optimization Impacts AI-Driven Fashion Design

Explore how Next.js optimization enhances AI-driven fashion design, improving user experience and boosting sales.
277
0
0