Install & Configure Laravel Sanctum For API Authentication

Alex Johnson
-
Install & Configure Laravel Sanctum For API Authentication

In this comprehensive guide, we'll walk through installing and configuring Laravel Sanctum, a lightweight authentication system perfect for single-page applications (SPAs), mobile applications, and simple API authentication. If you're building a modern web application with a separate frontend and backend, such as a React application with a Laravel API, Sanctum provides a secure and straightforward way to manage API tokens.

Understanding the Need for Laravel Sanctum

When building modern web applications, especially those with separate frontends like React and backend APIs built with Laravel, traditional session-based authentication mechanisms fall short. Traditional web applications rely on sessions and cookies for authentication, requiring the server to remember who you are between requests. In contrast, token-based authentication, which Laravel Sanctum facilitates, is more suitable for applications with decoupled frontends and backends. With Sanctum, the server issues API tokens to users upon successful authentication. These tokens act as temporary passwords that prove the user's identity in subsequent requests. This is particularly crucial for Single Page Applications (SPAs) needing special authentication considerations.

Unlike the traditional session-based authentication that relies on stateful mechanisms, API token authentication provided by Laravel Sanctum is stateless. This distinction is critical because, in stateful authentication, the server needs to maintain session data for each user. This can lead to scalability issues and complexities when dealing with multiple servers or microservices. In contrast, stateless authentication relies on the token itself containing all the necessary information to verify the user's identity. This eliminates the need for the server to maintain session data, making it easier to scale and manage the application.

Using Sanctum, the frontend sends the API token in the Authorization header of each request. The backend then validates this token to ensure that the user is authenticated. This approach provides a secure and scalable way to authenticate users in modern web applications. It also allows you to easily implement different authentication strategies for different parts of your application. For example, you can use Sanctum for your API routes while still using traditional session-based authentication for your web routes.

Acceptance Criteria

By the end of this guide, you will be able to:

  • Install Sanctum using composer require laravel/sanctum.
  • Publish Sanctum's configuration and migrations using php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider".
  • Run the Sanctum migrations with php artisan migrate.
  • Add Sanctum's middleware to your API middleware group in app/Http/Kernel.php.
  • Configure CORS (Cross-Origin Resource Sharing) in config/cors.php to allow requests from your React application's domain.
  • Add the HasApiTokens trait to your User model.

Step-by-Step Installation and Configuration

Step 1: Install Sanctum via Composer

The first step is to install Laravel Sanctum using Composer, the PHP dependency manager. Open your terminal, navigate to your Laravel project's root directory, and run the following command:

composer require laravel/sanctum

This command downloads the Sanctum package and adds it to your project's dependencies. Composer makes it easy to manage the various libraries and packages that your Laravel application depends on. It ensures that the correct versions of these dependencies are installed and that they are compatible with each other. The composer require command also updates the composer.json file in your project's root directory, which lists all of your project's dependencies.

After running this command, Composer automatically updates the autoload.php file, making the Sanctum classes available to your application. You can then proceed to the next step, which involves publishing Sanctum's configuration and migration files.

Step 2: Publish Configuration and Migration Files

Once Sanctum is installed, you need to publish its configuration and migration files. These files allow you to customize Sanctum's behavior and set up the necessary database tables. Run the following command in your terminal:

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

This command copies the configuration file (config/sanctum.php) and the migration file from the Sanctum package to your application. The vendor:publish command is a powerful tool that allows you to easily customize the behavior of various packages in your Laravel application. By publishing the configuration and migration files, you can modify them to suit your specific needs.

The configuration file contains various options that control how Sanctum behaves. For example, you can configure the expiration time for API tokens, the database table used to store tokens, and the middleware used to protect your API routes. The migration file contains the schema for the personal_access_tokens table, which is used to store the API tokens. You can modify this schema to add additional columns or indexes as needed.

Step 3: Run Database Migrations

After publishing the migration file, you need to run the database migrations to create the personal_access_tokens table. This table will store the API tokens that Sanctum generates. Run the following command in your terminal:

php artisan migrate

This command executes all pending migrations in your application, including the Sanctum migration. Laravel's migration system provides a convenient way to manage your database schema. Migrations allow you to easily create, modify, and drop database tables in a consistent and repeatable manner. This is especially useful when working in a team environment, as it ensures that everyone is using the same database schema.

After running the php artisan migrate command, the personal_access_tokens table will be created in your database. This table contains the following columns:

  • id: The primary key of the table.
  • tokenable_type: The type of the model that the token belongs to (e.g., App\Models\User).
  • tokenable_id: The ID of the model that the token belongs to (e.g., the user ID).
  • name: The name of the token.
  • token: The API token itself (hashed for security).
  • abilities: A JSON array of abilities that the token has.
  • last_used_at: The last time the token was used.
  • expires_at: The expiration time of the token.
  • created_at: The timestamp when the token was created.
  • updated_at: The timestamp when the token was last updated.

Step 4: Configure Middleware

Next, you need to add Sanctum's middleware to your API middleware group in app/Http/Kernel.php. This middleware is responsible for authenticating incoming requests using the API tokens. Open the app/Http/Kernel.php file and locate the $middlewareGroups array. Add \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class to the 'api' middleware group:

'api' => [
    \App\Http\Middleware\EncryptCookies::class,
    \Illuminate\Session\Middleware\StartSession::class,
    \Illuminate\View\Middleware\ShareErrorsFromSession::class,
    \App\Http\Middleware\VerifyCsrfToken::class,
    \Illuminate\Routing\Middleware\SubstituteBindings::class,
    \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class, // Add this line
],

Middleware in Laravel act as intermediaries that filter HTTP requests entering your application. They examine the request and can perform actions like authentication, logging, or modifying the request before it reaches your application's logic. Sanctum's middleware, EnsureFrontendRequestsAreStateful, specifically checks for a valid API token in the request headers. If a token is present and valid, the middleware authenticates the user and allows the request to proceed. If no token is present or the token is invalid, the middleware may reject the request or redirect the user to a login page.

Step 5: Configure CORS

CORS (Cross-Origin Resource Sharing) is a browser security feature that prevents JavaScript on one domain from accessing resources on another domain. Since your React application and Laravel API likely run on different domains (e.g., localhost:5173 and localhost:8000 respectively), you need to configure CORS to allow requests from your React application to your Laravel API. Open the config/cors.php file and configure the allowed origins, methods, and headers:

'paths' => ['api/*'],

'allowed_methods' => ['*'],

'allowed_origins' => [
    'http://localhost:5173',
],

'allowed_origins_patterns' => [],

'allowed_headers' => ['*'],

'exposed_headers' => [],

'supports_credentials' => false,

'max_age' => 0,

CORS is a critical security feature that prevents malicious websites from making unauthorized requests to your API. By configuring CORS, you can specify which origins are allowed to access your API resources. This prevents attackers from exploiting vulnerabilities in your API and gaining access to sensitive data.

In the config/cors.php file, the 'paths' => ['api/*'] configuration means that the CORS rules apply to all routes starting with /api. The 'allowed_origins' array specifies the origins that are allowed to make requests to your API. In this case, we've added http://localhost:5173, which is the development server for our React application.

Step 6: Add the HasApiTokens Trait to Your User Model

Finally, you need to add the HasApiTokens trait to your User model. This trait provides the methods necessary to create and manage API tokens. Open the app/Models/User.php file and add the HasApiTokens trait:

namespace App\Models;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens; // Add this line

class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable; // Update this line

    // ...
}

Traits in PHP are a mechanism for code reuse in single inheritance languages such as PHP. A Trait is intended to reduce the limitations of single inheritance by enabling a developer to reuse sets of methods freely in several independent classes living in different class hierarchies. The HasApiTokens trait injects methods into your User model that let you create, retrieve, and manage API tokens associated with a user. This includes the crucial createToken() method which you will use to issue tokens to authenticated users.

Conclusion

You have successfully installed and configured Laravel Sanctum for API authentication. You can now issue API tokens to your users and use those tokens to authenticate requests to your API. This provides a secure and scalable way to authenticate users in your modern web application.

By following these steps, you've learned how to integrate Laravel Sanctum into your application, providing a robust and secure way to handle API authentication. Remember to always keep your dependencies up to date and follow security best practices to protect your application and user data.

For more information on Laravel Sanctum, check out the official Laravel Sanctum Documentation.

You may also like