DEV Community

Cover image for Day 6: Building APIs with Laravel Sanctum
Ehtesham Ali
Ehtesham Ali

Posted on

Day 6: Building APIs with Laravel Sanctum

APIs are the backbone of modern applications, enabling seamless communication between different platforms. Laravel Sanctum provides a lightweight authentication system for securing APIs and building robust, scalable applications. In this blog, we'll explore Sanctum, how to set it up, and its common use cases, including SPAs and token-based authentication.

What is Laravel Sanctum?

Laravel Sanctum is a simple package for API authentication that offers two main capabilities:

  • Token-based Authentication: Suitable for APIs accessed by third-party services or mobile apps.

  • Session-based Authentication: Ideal for single-page applications (SPAs) where the frontend and backend share the same domain.

Unlike heavier alternatives like Laravel Passport, Sanctum is lightweight, easy to configure, and tailored for applications that don’t require OAuth features.

Setting Up Laravel Sanctum

Step 1: Install Sanctum

To begin, install Sanctum via Composer:

composer require laravel/sanctum
Enter fullscreen mode Exit fullscreen mode

Step 2: Publish Sanctum Configuration

Publish the Sanctum configuration file:

php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
Enter fullscreen mode Exit fullscreen mode

This will create a config/sanctum.php file where you can customize Sanctum's settings.

Step 3: Run Migrations

Sanctum uses a personal_access_tokens table to store issued tokens. Run the following command to create this table:

php artisan migrate
Enter fullscreen mode Exit fullscreen mode

Step 4: Configure Middleware

Add Sanctum’s middleware to your api middleware group in app/Http/Kernel.php:

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

Implementing Token-Based Authentication

Step 1: Protecting Routes

Define protected routes in your routes/api.php file. Use the auth:sanctum middleware to secure them:

use Illuminate\Support\Facades\Route;

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

Step 2: Generating Tokens

You can issue personal access tokens for a user using the createToken method:

use App\Models\User;
use Illuminate\Http\Request;

Route::post('/login', function (Request $request) {
    $user = User::where('email', $request->email)->first();

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

    return $user->createToken('auth_token')->plainTextToken;
});
Enter fullscreen mode Exit fullscreen mode

Step 3: Revoking Tokens

Revoke a user's token to log them out:

Route::post('/logout', function (Request $request) {
    $request->user()->tokens()->delete();
    return response()->json(['message' => 'Logged out successfully']);
});
Enter fullscreen mode Exit fullscreen mode

Use Case: Single-Page Applications (SPAs)

For SPAs, Sanctum uses session-based authentication. Here's how to set it up:

Step 1: Enable CSRF Protection

Ensure Sanctum's EnsureFrontendRequestsAreStateful middleware is correctly configured in api middleware.

Step 2: Configure Frontend

Make authenticated AJAX requests from your SPA by sending the CSRF token:

axios.defaults.withCredentials = true;

axios.get('/sanctum/csrf-cookie').then(() => {
    axios.post('/login', {
        email: 'example@example.com',
        password: 'password'
    });
});
Enter fullscreen mode Exit fullscreen mode

Best Practices

  • Secure Your Tokens: Store tokens securely (e.g., in HTTP-only cookies) and avoid exposing them to client-side scripts.

  • Set Token Expiration: Use token expiration to minimize risks if a token is leaked.

  • Limit Token Scopes: Define specific scopes for tokens to restrict their permissions.

Conclusion

Laravel Sanctum makes it easy to secure APIs for modern applications. Whether you're building a SPA or providing token-based access to third-party apps, Sanctum offers a powerful yet lightweight solution. With minimal configuration and a flexible API, Sanctum simplifies authentication for developers.

Feel free to try out Sanctum in your projects and explore its capabilities further!

Top comments (0)