2024-11-228 minLaravel

Building RESTful APIs with Laravel Sanctum

Learn how to secure your RESTful APIs in Laravel using Sanctum. We'll explore authentication, token management, and tips for building robust APIs.

Introduction

In modern web development, building secure and efficient RESTful APIs is crucial, especially when handling user authentication and sensitive data. Laravel Sanctum offers a lightweight authentication system, perfect for single-page applications (SPAs), mobile applications, and simple token-based APIs. In this guide, we'll cover how to set up Laravel Sanctum, create authentication routes, and manage tokens for securing API requests.

What is Laravel Sanctum?

Laravel Sanctum provides a simple way to authenticate single-page applications (SPAs), mobile applications, and token-based APIs. It enables applications to issue and manage tokens for individual users, making it ideal for securing APIs without complex OAuth setups.

Step 1: Installing Sanctum

To start, install Sanctum using Composer. Run the following command in your Laravel project:

composer require laravel/sanctum

After installation, publish the Sanctum configuration file:

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

Then, migrate the necessary database tables for Sanctum:

php artisan migrate

Step 2: Configuring Sanctum

In the config/sanctum.php file, you can adjust Sanctum's settings, including token expiration and cookie domains. For most API uses, the default settings are adequate.

Middleware

To apply Sanctum's authentication middleware, add it to your API routes in routes/api.php:

use Illuminate\Http\Request;

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

This middleware ensures that only authenticated users can access the specified routes.

Step 3: Issuing Tokens

Sanctum allows each user to have multiple tokens for different devices or applications. Tokens can be created using the createToken method in a controller:

$user = User::find(1);
$token = $user->createToken('api-token')->plainTextToken;

This token can then be used in API requests by adding it as a Bearer token in the request header.

Step 4: Securing API Endpoints

Now that tokens can be issued, secure your API endpoints by applying the auth:sanctum middleware to routes that require authentication:

Route::middleware('auth:sanctum')->group(function () {
    Route::get('/dashboard', [DashboardController::class, 'index']);
    Route::post('/logout', [AuthController::class, 'logout']);
});

This approach keeps routes restricted to authenticated users with valid tokens.

Step 5: Testing API with Sanctum

To test your API with Sanctum, use tools like Postman or cURL. Add the generated token to the Authorization header as a Bearer token:

GET /api/user
Authorization: Bearer {YOUR_TOKEN_HERE}

Conclusion

Laravel Sanctum is a powerful tool for building secure, RESTful APIs without complex setup. By following the steps above, you can create authenticated API endpoints, manage tokens for your users, and build scalable applications with robust authentication.

Whether you're developing a mobile app or SPA, Sanctum provides an easy-to-use solution that integrates seamlessly with Laravel.