Sanctum Integration

This tutorial will demonstrate how to use Sanctum for Laravel API authentication.

Introduction

Laravel Sanctum offers a lightweight authentication system for mobile apps, token-based APIs, and single page applications (SPAs). Every user of your application can create several API tokens for their account with Sanctum. These tokens might be given scopes or abilities that define what kinds of actions they can carry out.

Installation

The most recent versions of Laravel already include Laravel Sanctum. However, if your application's composer.json file does not include laravel/sanctum, you may follow the installation instructions below.

  1. Using the Composer package manager, you can install Laravel Sanctum.

composer require laravel/sanctum
  1. Next, you should publish the Sanctum configuration and migration files using the vendor:publish Artisan command. The sanctum configuration file will be placed in your application's config directory:

php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
  1. Next, in your application's app/Http/Kernel.php file, add Sanctum's middleware to your api middleware group if you want to use it for SPA authentication:

'api' => [
    \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
    'throttle:api',
    \Illuminate\Routing\Middleware\SubstituteBindings::class,
],
  1. You may use Sanctum to issue personal access tokens and API tokens, which you can use to authenticate API queries to your application. When utilizing API tokens for requests, the token needs to be supplied as a Bearer token in the Authorization header.

  2. To begin issuing tokens for users, your User model should use the Laravel\Sanctum\HasApiTokens trait:

  3. HasApiTokens adds in User model file.according to below example:

use Laravel\Sanctum\HasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;
}
  1. Then, in your application's config/auth.php configuration file, you should add the driver option for the api authentication guard.

'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'users',
    ],

    'api' => [
        'driver' => 'sanctum',
        'provider' => 'users',
        'hash' => false,
    ],
],
  1. Executing your database migrations should be your final step. In order to hold API tokens, Sanctum will make one database table:

php artisan migrate

Last updated