Consent

This site uses third party services that need your consent.

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.

More posts

Simplifying Laravel Development with Laravel Sail

Laravel Sail is a lightweight CLI for managing Laravel's Docker development environment. It simplifies running Artisan commands, PHP scripts, tests, and database operations. Key uses include local development, CI/CD pipelines, team collaboration, and multi-version PHP testing. Best practices involve using aliases, customizing services, and regular updates.