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.
Using the Composer package manager, you can install Laravel Sanctum.
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:
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:
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.
To begin issuing tokens for users, your
User
model should use theLaravel\Sanctum\HasApiTokens
trait:HasApiTokens
adds in User model file.according to below example:
Then, in your application's
config/auth.php
configuration file, you should add the driver option for the api authentication guard.
Executing your database migrations should be your final step. In order to hold API tokens, Sanctum will make one database table:
Last updated