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

Streamlining Local Development with Laravel Valet

Laravel Valet is a lightweight development environment for macOS, simplifying local PHP project setup and management. Key features include easy site serving, HTTPS support, site sharing, and custom domain linking. Suggested uses include rapid prototyping, multi-framework development, and API testing. Best practices involve using different PHP versions, customizing Nginx configs, and regular updates.

Rising Above Circumstance: Choosing Our Own Destiny

Inspired by Stephenie Meyer's quote, this post explores the power of personal choice in shaping our destiny. It challenges the notion of predetermined fate and offers strategies for overcoming limitations to create the life we desire.

Building a Simple Marketing Website with Laravel Folio

Learn to build a simple marketing website using Laravel Folio. Set up a Laravel project, install Folio, create pages with Blade templates, and maintain consistency with layouts. Quickly create dynamic content for your marketing site.