Skip to content
Steven Roland

Securing Your Laravel API with Sanctum: A Comprehensive Guide

Laravel Sanctum is a powerful, lightweight authentication system for SPAs (Single Page Applications), mobile applications, and simple, token-based APIs. It provides a seamless way to handle API token authentication without the complexity of OAuth. In this post, we'll explore how to set up and use Sanctum, along with some practical examples and best practices.

Getting Started with Laravel Sanctum

First, let's install Sanctum in your Laravel project:

composer require laravel/sanctum

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

php artisan migrate

Next, add the Sanctum middleware to your app/Http/Kernel.php file:

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

Implementing API Token Authentication

  1. Creating Tokens

    To create an API token for a user, you can use the createToken method:

    use App\Models\User;
    
    $user = User::find(1);
    $token = $user->createToken('api-token')->plainTextToken;
  2. Authenticating Requests

    To authenticate API requests, include the token in the Authorization header:

    Authorization: Bearer {your-token}
  3. Protecting Routes

    Protect your API routes using the auth:sanctum middleware:

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

SPA Authentication

For SPA authentication, Sanctum uses Laravel's built-in cookie-based session authentication. Here's how to set it up:

  1. Configure your config/sanctum.php file:

    'stateful' => explode(',', env('SANCTUM_STATEFUL_DOMAINS', sprintf(
        '%s%s',
        'localhost,localhost:3000,127.0.0.1,127.0.0.1:8000,::1',
        env('APP_URL') ? ','.parse_url(env('APP_URL'), PHP_URL_HOST) : ''
    ))),
  2. In your SPA, make a request to the /sanctum/csrf-cookie endpoint before logging in:

    axios.get('/sanctum/csrf-cookie').then(response => {
        // Login...
    });
  3. Implement login functionality:

    public function login(Request $request)
    {
        $request->validate([
            'email' => 'required|email',
            'password' => 'required',
        ]);
    
        if (Auth::attempt($request->only('email', 'password'))) {
            return response()->json(Auth::user(), 200);
        }
    
        throw ValidationException::withMessages([
            'email' => ['The provided credentials are incorrect.'],
        ]);
    }

Suggested Usages

  • Mobile App Authentication: Use API tokens for authenticating mobile app requests.

    public function loginMobile(Request $request)
    {
        $request->validate([
            'email' => 'required|email',
            'password' => 'required',
        ]);
    
        $user = User::where('email', $request->email)->first();
    
        if (! $user || ! Hash::check($request->password, $user->password)) {
            throw ValidationException::withMessages([
                'email' => ['The provided credentials are incorrect.'],
            ]);
        }
    
        return $user->createToken('mobile-token')->plainTextToken;
    }
  • Microservices Communication: Use Sanctum tokens for secure communication between microservices.

  • Third-party API Integration: Generate long-lived tokens for third-party services to access your API.

    $token = $user->createToken('third-party-token', ['read'], now()->addYear())->plainTextToken;
  • Scoped Permissions: Implement token abilities for fine-grained access control.

    Route::middleware(['auth:sanctum', 'ability:check-status'])->get('/status', function () {
        return response()->json(['status' => 'active']);
    });

Best Practices

  • Token Expiration: Set appropriate expiration times for tokens based on their use case.

  • HTTPS: Always use HTTPS in production to protect token transmission.

  • Token Revocation: Implement token revocation on logout or when compromised.

  • Rate Limiting: Apply rate limiting to prevent abuse of your API.

Laravel Sanctum provides a robust, flexible solution for API authentication in Laravel applications. By leveraging its features and following best practices, you can create secure, scalable APIs that support various authentication flows. Whether you're building a SPA, mobile app, or microservices architecture, Sanctum offers the tools to implement effective authentication with minimal overhead.

Support My Work

If you enjoy my content, consider supporting me through Buy Me a Coffee or GitHub Sponsors.

Buy Me A Coffee
or

More posts

Laravel's unique Validation Rule: Advanced Usage and Exceptions

This post explains Laravel's advanced unique validation rule, focusing on the unique:table,column,except,idColumn syntax. It provides real-world examples for updating user profiles, product SKUs, and organization subdomains, along with best practices and considerations.

Living Fully: Embracing Life Beyond the Fear of Death

Inspired by Natalie Babbitt's quote, this post explores the importance of living fully rather than fearing death. It offers insights on what constitutes a well-lived life and provides strategies for embracing each moment with authenticity and purpose.