Setting up Sactum for Multi Auth Entities in Laravel v10 using Guard

WebhortizWebhortiz
2 min read

if you have heard or read about Laravel Passport or JWTs (Json Web Tokens) then Laravel Sanctum or for short Sanctum should be thought of as lightweight version of Passport.

While both Passport and Sanctum are used in authentication there are key differences which makes one preferable over the other but area of application is a major determinant. i.e when building a product that its auth system has to do with Oauth2, Passport becomes the best choice as Sanctum is just token based.

Key Difference between Sanctum and Passport:

SanctumPassport
Its token based onlyHas good support for Oauth2
Easier to setupA bit complex to scaffold
Good fo SPAs

Setting up Sactum in Laravel v10

As Sanctum already comes with Laravel out of the box. Assuming you have 3 seperate entities Administrator, Vendor, User and you want to make different modules for each using seperate auth table.

Making Model

Create a model for Administrator, Vendor and User

php artisan make:model {modelName} -mcr

Note:*replace {modelName} with actual model name e.g Administrator*

where -mcr stands for

  • m: migration

  • c: controller

  • r: resource

importhasApiTokenstrait and extendAuthenticatable

<?php

namespace App\Models\Administrator;

use Illuminate\Database\Eloquent\Concerns\HasUlids;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Laravel\Sanctum\HasApiTokens;

class Administrator extends Authenticatable
{
    use HasFactory, HasApiTokens, HasUlids;
}

Configure config/auth.php

Add desired guards and specify a provider

'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],
        'admin' => [
            'driver' => 'session',
            'provider' => 'admins',
        ],
        'vendor' => [
            'driver' => 'session',
            'provider' => 'vendors',
        ],
    ],

Configuring providers

'providers' => [
        'users' => [
            'driver' => 'eloquent',
            'model' => User::class,
        ],
        'admins' => [
            'driver' => 'eloquent',
            'model' => Administrator::class,
        ],
        'vendors' => [
            'driver' => 'eloquent',
            'model' => Vendor::class,
        ],
    ],

Note: You might specify a different password_reset_token table in the same file.

Identifying a specific user request through Guard and creating a sactum auth token.

  • Registering User
public function register(Request $request) : JsonResponse {
        $admin = Administrator::create([
            'firstname' => $request->firstname,
            'lastname' => $request->lastname,
            'phone' => isset($request->phone) ? $request->phone : null,
            'email' => $request->email,
            'password' => Hash::make($request->password),
        ]);
        $admin->createToken('Code with Soneye')->plainTextToken;
        return response()->json($admin, 201);
    }
  • Logging in with an Administrator
public function login(LoginRegisterRequest $request) : JsonResponse {
        $credentials = $request->only('email', 'password');
        if (Auth::guard('admin')->attempt($credentials)) {
            $token = Auth::guard('admin')->user()->createToken('Code with SOneye')->plainTextToken;
            return response()->json($token, 200);
        }
    }

To validated request on postman, attach generated response token to beare auth

Protecting route with sanctum

Use the auth:sanctum middleware

Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
    return $request->user();
});

Thanks.

0
Subscribe to my newsletter

Read articles from Webhortiz directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Webhortiz
Webhortiz