Laravel-9 Multi Authentication Guard Passport API Example

  • 22-07-2022
  • 3228
  • Laravel 9
  • Haresh Chauhan

Passport API multiple authentications using the custom create guard in laravel 9; In this post, I will learn you how to make multiple auth with custom guard setting using passport API token.

I will teach you, How to build a multiple guards authentication API in laravel 9 Using a passport. We will create multiple authentication APIs with custom created guard. Having read this article you will get how to authenticate guard driver and setup passport in laravel API and get an access token for access to authorize API from this project.

Laravel 9 multiple auth API using passport tool and create custom guard for multi authentication from this tutorial you will learn. So just follow the step and apply in your project.

However, if you want to create API authentication using a passport laravel provides very easy and simple to use, But the challenge is multiple user authentication in laravel using a passport tool with a custom guard.

Default Laravel provides passport user authentication, But in your application has more than one user and you want to make them separate and want to make them different authentication that while a little bit difficult.

Default laravel 9 user auth. We have user passport authentication already available, but I want to create a doctor authentication separate from the user. In this article, I have taken the example of separate doctor authentication. Just follow step by step process and you will easily to multiple authentication APIs in your application with a custom guard.

So let's start with how to passport integrates with multiple user API authentications?.

Step 1: Create Laravel Project

Create laravel 9 projects using the given suggested below command in your terminal. This will take a little time to create a laravel project in your system. This command default will take current version of the laravel.

composer create-project laravel/laravel passport

//cd passport

Step 2: Config Database

After Successfully creating the laravel project we will config our database. First, I will go to my PHPMyAdmin and create a passport name database.

Then we will put this passport database name in the .env file you will find in your root file. If not found the .env file in your root just create and copy form .env.example file and config.

Laravel 9 Create Custom Auth Guard Multi Login Authentication System Tutorial

.env
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=passport
DB_USERNAME=root
DB_PASSWORD=

Step 3: Passport Install

Copy below give the command and paste it into your project root directory terminal. This command will install composer for passport authentication tool in our project.

composer require laravel/passport

Step 4: Make Doctor Model & Migration

We will create a model, migration for the doctor login system. Using the below-given command it will create a model and migration for the doctor.

php artisan make:model Doctor -m

Added some doctor basic details column in the table for collecting doctor registration and log in authentication.

database/migrations/2022_07_21_152830_create_doctors_table.php
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateDoctorsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('doctors', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email');
            $table->string('username');
            $table->string('password');
            $table->enum('status',['active','inactive'])->default('active');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('doctors');
    }
}

After the doctor migration, we will migrate all our migrations in our database using the below command. just cope with this command it will migrate all tables into your database.

php artisan migrate

Then, We will install the passport in your laravel application using the below given suggested command passport: install this command will create some basic config setting files in the application for the use passport tool.

php artisan passport:install

Step 5: Passport Config In Model

After, We will be setting both User and Doctor model.

First we will import use Laravel\Passport\HasApiTokens; in both model. and use it inside the class. If you want to use notification in your system for the use you can also import it and use else not needed.

app/Models/User.php
<?php

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\Passport\HasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;

    /**
        * The attributes that are mass assignable.
        *
        * @var array
        */
    protected $fillable = [
        'name',
        'email',
        'password',
    ];

    /**
        * The attributes that should be hidden for serialization.
        *
        * @var array
        */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
        * The attributes that should be cast.
        *
        * @var array
        */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];
}
    

In Doctor model, First we will extends to Authenticatable and then we will import use Laravel\Passport\HasApiTokens; and use it inside the class.

app/Models/Doctor.php
<?php
namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Passport\HasApiTokens;

class Doctor extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;

    protected $fillable = [
        'name',
        'email',
        'username',
        'password',
        'status',
    ];
}

Step 6: Setting AuthServiceProvider

Goto AuthServiceProvider file, Inside the boot() method setting passport. Remember not to forget to use Laravel\Passport\Passport; in this class.

You can define all the users which you want for their authentication inside the Passport::tokensCan().

Here you can see that I want to create two auth so used two only.

app/Providers/AuthServiceProvider.php
<?php

namespace App\Providers;

use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Gate;
use Laravel\Passport\Passport;

class AuthServiceProvider extends ServiceProvider
{
    /**
        * The policy mappings for the application.
        *
        * @var array
        */
    protected $policies = [
        // 'App\Models\Model' => 'App\Policies\ModelPolicy',
    ];

    /**
        * Register any authentication / authorization services.
        *
        * @return void
        */
    public function boot()
    {
        $this->registerPolicies();

        Passport::routes();

        Passport::tokensCan([
            'user' => 'User',
            'doctor' => 'Doctor',
        ]);
    }
}

Step 7: Setting Guard

In this step, we will create a custom guard for that user for who`m we want to create auth with guard.

We just need to define two attributes for each use first user and second user-api and provider attribute just we will define our provider and define the model for the user.

config/auth.php
<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Authentication Defaults
    |--------------------------------------------------------------------------
    |
    | This option controls the default authentication "guard" and password
    | reset options for your application. You may change these defaults
    | as required, but they're a perfect start for most applications.
    |
    */

    'defaults' => [
        'guard' => 'web',
        'passwords' => 'users',
    ],

    /*
    |--------------------------------------------------------------------------
    | Authentication Guards
    |--------------------------------------------------------------------------
    |
    | Next, you may define every authentication guard for your application.
    | Of course, a great default configuration has been defined for you
    | here which uses session storage and the Eloquent user provider.
    |
    | All authentication drivers have a user provider. This defines how the
    | users are actually retrieved out of your database or other storage
    | mechanisms used by this application to persist your user's data.
    |
    | Supported: "session"
    |
    */

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

        // FOR USER

        'user' => [
            'driver' => 'session',
            'provider' => 'users',
        ],

        'user-api' => [
            'driver' => 'passport',
            'provider' => 'users',
        ],

        //  FOR DOCTOR

        'doctor' => [
            'driver' => 'session',
            'provider' => 'doctors',
        ],
    
        'doctor-api' => [
            'driver' => 'passport',
            'provider' => 'doctors',
        ],
    ],

    /*
    |--------------------------------------------------------------------------
    | User Providers
    |--------------------------------------------------------------------------
    |
    | All authentication drivers have a user provider. This defines how the
    | users are actually retrieved out of your database or other storage
    | mechanisms used by this application to persist your user's data.
    |
    | If you have multiple user tables or models you may configure multiple
    | sources which represent each model / table. These sources may then
    | be assigned to any extra authentication guards you have defined.
    |
    | Supported: "database", "eloquent"
    |
    */

    'providers' => [
        'users' => [
            'driver' => 'eloquent',
            'model' => App\Models\User::class,
        ],

        // ADD DOCTOR PROVIDER 

        'doctors' => [
            'driver' => 'eloquent',
            'model' => App\Models\Doctor::class,
        ],

    ],

    /*
    |--------------------------------------------------------------------------
    | Resetting Passwords
    |--------------------------------------------------------------------------
    |
    | You may specify multiple password reset configurations if you have more
    | than one user table or model in the application and you want to have
    | separate password reset settings based on the specific user types.
    |
    | The expire time is the number of minutes that each reset token will be
    | considered valid. This security feature keeps tokens short-lived so
    | they have less time to be guessed. You may change this as needed.
    |
    */

    'passwords' => [
        'users' => [
            'provider' => 'users',
            'table' => 'password_resets',
            'expire' => 60,
            'throttle' => 60,
        ],
    ],

    /*
    |--------------------------------------------------------------------------
    | Password Confirmation Timeout
    |--------------------------------------------------------------------------
    |
    | Here you may define the amount of seconds before a password confirmation
    | times out and the user is prompted to re-enter their password via the
    | confirmation screen. By default, the timeout lasts for three hours.
    |
    */

    'password_timeout' => 10800,

];

Step 8: Scope Add In Middleware

In this step, we will define scop inside the route middleware for the passport authentication API.

Just go to your kernel file and add these two scopes in side the routeMiddleware protected variable. This scope we will use in our route file in the next step.

app/Http/Kernel.php
protected $routeMiddleware = [
    'scopes' => \Laravel\Passport\Http\Middleware\CheckScopes::class,
    'scope' => \Laravel\Passport\Http\Middleware\CheckForAnyScope::class,
];

Step 9: Register Route In RouteServiceProvider

Goto RouteServiceProvider file and setting inside the boot() method.

First we will create user.php and doctor.php file inside the routes folder and then we will define here. You can just copy and paste in your application and config yourself according to your requirements.

Remember this config is only for the laravel 9, If you are using a lower version then it little bit different from here. But the setting same.

app/Providers/RouteServiceProvider.php
<?php

namespace App\Providers;

use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Facades\Route;

class RouteServiceProvider extends ServiceProvider
{
    /**
        * The path to the "home" route for your application.
        *
        * This is used by Laravel authentication to redirect users after login.
        *
        * @var string
        */
    public const HOME = '/home';

    /**
        * The controller namespace for the application.
        *
        * When present, controller route declarations will automatically be prefixed with this namespace.
        *
        * @var string|null
        */
    // protected $namespace = 'App\\Http\\Controllers';

    /**
        * Define your route model bindings, pattern filters, etc.
        *
        * @return void
        */
    public function boot()
    {
        $this->configureRateLimiting();

        $this->routes(function () {

            Route::prefix('api')
                ->middleware('api')
                ->namespace($this->namespace)
                ->group(base_path('routes/user.php')); // CREATE routes/user.php file

            Route::prefix('api')
                ->middleware('api')
                ->namespace($this->namespace)
                ->group(base_path('routes/doctor.php')); // CREATE routes/doctor.php file

            Route::middleware('web')
                ->namespace($this->namespace)
                ->group(base_path('routes/web.php'));
        });
    }

    /**
        * Configure the rate limiters for the application.
        *
        * @return void
        */
    protected function configureRateLimiting()
    {
        RateLimiter::for('api', function (Request $request) {
            return Limit::perMinute(60)->by(optional($request->user())->id ?: $request->ip());
        });
    }
}

Step 10: User Routes

Now, we will create a user controller, Just run the below command it will create a user login controller.

php artisan make:controller UserLoginController  

First, We will create a post API for the authentication, After receiving accessToken from this API we can access the dashboard from it.

routes/user.php
<?php

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\UserLoginController;
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/

// UNAUTH API FOR USE LOGIN
Route::post('user/login',[UserLoginController::class, 'userLogin'])->name('user.login');

// AUTHENTICATION API FOR USE
Route::group( ['prefix' => 'user','middleware' => ['auth:user-api','scopes:user'] ],function(){
    
    Route::post('dashboard',[UserLoginController::class, 'userDashboard'])->name('user.dashboard');
}); 

Now, We will create two methods this these two routes first setting according to userLogin method for generating use access token.

app/Http/Controllers/UserLoginController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Auth;
use Validator;
use App\Models\User;

class UserLoginController extends Controller
{
    public function userLogin(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'email' => 'required|email',
            'password' => 'required',
        ]);
        
        if($validator->fails()){

            return response()->json(['error' => $validator->errors()->all()]);
        }

        if(Auth::guard('user')->attempt(['email' => $request->email, 'password' => $request->password])){

            config(['auth.guards.api.provider' => 'user']);
            
            $token = Auth::guard('user')->user()->createToken('MyApp',['user'])->accessToken;
            
            return response()->json(['token' => $token], 200);

        }else{ 

            return response()->json(['error' => ['Email and Password are Wrong.']], 200);
        }
    }    

    public function userDashboard()
    {
        return response()->json(Auth::guard('user')->user());
    }
}

Step 11: Doctor Route

As same we used in the user also we will create a doctor controller using the below command.

php artisan make:controller DoctorLoginController

The same route created for the doctor first route is unauth for login this API will return the access token of the doctor and then you can access the doctor dashboard API for a given access token.

routes/doctor.php
<?php

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\DoctorLoginController;
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/

Route::post('doctor/login',[DoctorLoginController::class, 'doctorLogin'])->name('doctor.login');

Route::group( ['prefix' => 'doctor','middleware' => ['auth:doctor-api','scopes:doctor'] ],function(){

    Route::post('dashboard',[DoctorLoginController::class, 'doctorDashboard'])->name('doctor.dashboard');
}); 

Create doctor authentication method as below given snippet code, You just need to change guard name to doctor. for the doctor authentication.

app/Http/Controllers/UserLoginController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Validator;
use Auth;
use App\Models\Doctor;

class DoctorLoginController extends Controller
{
    public function doctorLogin(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'email' => 'required|email',
            'password' => 'required',
        ]);

        if($validator->fails()){

            return response()->json(['error' => $validator->errors()->all()]);
        }

        if(Auth::guard('doctor')->attempt(['email' => $request->email, 'password' => $request->password])){

            config(['auth.guards.api.provider' => 'doctor']);
            
            $token = Auth::guard('doctor')->user()->createToken('MyApp',['doctor'])->accessToken;
            
            return response()->json(['token' => $token], 200);

        }else{ 

            return response()->json(['error' => ['Email and Password are Wrong.']], 200);
        }
    }

    public function doctorDashboard()
    {
        return response()->json(Auth::guard('doctor')->user());
    }
}

Step 12: Make Seeder

Make a seeder to create a dummy user and doctor data. Just enter the below command in your terminal.

php artisan make:seeder UserSeeder

This command will generate a file in the seeder folder inside the database folder. I just added doctor and user test data.

database/seeders/UserSeeder.php
<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use App\Models\Doctor;
use App\Models\User;

class UserSeeder extends Seeder
{
    /**
        * Run the database seeds.
        *
        * @return void
        */
    public function run()
    {
        Doctor::create([
            'name' => 'Haresh Chauhan',
            'email' => 'haresh@gmail.com',
            'username' => 'haresh',
            'password' => bcrypt('123456')
        ]);

        User::create([
            'name' => 'Dharmesh Chauhan',
            'email' => 'dharmesh@gmail.com',
            'password' => bcrypt('123456')
        ]);
    }
}
    

Run the seeder using the below command in your terminal this will run your seeder and create a record in your database doctor and user table.

php artisan db:seed --class=UserSeeder

Step 13: Run Development Server

Well, all done now time to test multiple authentications with the custom guard doctor and user. First, we will start the development server. Enter this below-given command in our terminal.

php artisan serve

Before the first API in your posting must need config the header just like in the below image givn.

image

Run this API with form data email and password for the user to generate an access token.

http://127.0.0.1:8000/api/user/login
User Authentication postman view.

image

Run this API for the doctor to get an access token for doctor authentication.

http://127.0.0.1:8000/api/doctor/login
Doctor Authentication postman view.

image

Conclusion

This passport multiple user authentication API is a powerful tool of the laravel, This is one of the secure API authentications too for the large project. This is very easy to customize and unlimited use authenticate using this passport tool in laravel 9. If you working on a large project with API so I suggest you use the passport authentication tool. This is upgrading day by day more secure and popular in the laravel community in worldwide.


We always thanks to you for reading our blogs.


dharmesh-image

Dharmesh Chauhan

(Swapinfoway Founder)

Hello Sir, We are brothers origin from Gujarat India, Fullstack developers working together since 2016. We have lots of skills in web development in different technologies here I mention PHP, Laravel, Javascript, Vuejs, Ajax, API, Payment Gateway Integration, Database, HTML5, CSS3, and Server Administration. So you need our service Please Contact Us

haresh-image

Haresh Chauhan

(Co-Founder)


We Are Also Recommending You :