DEV Community

Remon Hasan
Remon Hasan

Posted on

Laravel 8 REST API Authentication with Sanctum

Alt Text

Source Code

Github

Laravel Sanctum, formerly known as Airlock, is a Laravel package created for the authentication of Single Page Applications (SPAs), mobile applications, and basic token-based APIs. It can be used to issue API Tokens to your users and authenticate Single Page Applications using Laravel's session.
we are going to create product api. For testing we will use the postman.

Model and Migration

First, we have to create a product model,migration,controller as like:

php artisan make:model Product -m
php artisan make:controller ProductController --api

Create the fields as like:

Alt Text

Migrate: Before migrate you should create the database in env file and connect to the MySql server or others you prefer.

php artisan migrate

Route

Second, we have to create a resource route in api.php as like:

Route::resource('products', ProductController::class);

Controller Functions

Alt Text

Alt Text

Alt Text

Postman Test

Create:

Alt Text

Update:

Alt Text

Validation:

Alt Text

Delete:

Alt Text

Search by Name:

Alt Text

Get by ID:

Alt Text

Sanctum Authentication and Access Token Generation

Install Sanctum:

composer require laravel/sanctum

Vendor Publish for access token migration:

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

Migrate:

php artisan migrate

setup

Go to app, then kernel.php and add the given lines in api array section. also for query you can follow laravel Sanctum Documentation

Alt Text

Add to User Model: Go to User.php and add the lines:

use Laravel\Sanctum\HasApiTokens;

use HasFactory, Notifiable, HasApiTokens;

Create a group route function which will include the protected routes:

Alt Text

Create Controller

php artisan make:controller AuthController

Register Function

Alt Text

Postman Test:

Alt Text

Get Product access by token:

Alt Text

Now add logout: After logout the token will be deleted.

`public function logout(Request $request) {
auth()->user()->tokens()->delete();

    return [
        'message' => 'Logged out'
    ];
}` 
Enter fullscreen mode Exit fullscreen mode

Create logout route:

Route::post('/logout', [AuthController::class, 'logout']);

Postman Test:

Alt Text

Login

Create route for login as like:

Route::post('/login', [AuthController::class, 'login']);

Login Function:

Alt Text

Logged in:

Alt Text

All Public and Protected Route

Alt Text

Latest comments (0)