Building Secure APIs with Laravel Sanctum

TECHNOLOGY
88 Views
Akorede Ogunsola
Posted on June 3, 2025
Building Secure APIs with Laravel Sanctum

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! 🚀

Comments

Login to write a comment
Loading...

© 2025 Collaboration Chronology. All rights reserved.

ContactTerms of ServicePrivacy PolicyCookies Policy