Laravel 10 - Multi Authentication API with Example

28-Apr-2023

.

Admin

Laravel 10 - Multi Authentication API with Example

Hi Friends,

In this tutorial, I would like to share with you build a multiple guards authentication API in Laravel 10. We will create multiple authentication APIs in Laravel 10. This article will give you multiple authentication guard drivers (including API) in Laravel 10. how to set up multi-auth for Laravel 10 apis. We will show how to use multiple authentication guards in a Laravel 10 API.

In this post, I will show you Laravel provides an easy way to create API. If you have authentication in your mobile app then you can easily do it using the passport. Laravel 10 Passport provides a way to create auth token for validating users.

If you also want to create a rest API for your mobile application then you can follow this tutorial for how to use multiple authentication guards in a Laravel 10 API. Here I am creating client and user guards.

Step 1: Download Laravel


Let us begin the tutorial by installing a new Laravel application. if you have already created the project, then skip the following step.

composer create-project laravel/laravel example-app

Step 2: Database Configuration

.env

DB_CONNECTION=mysql

DB_HOST=127.0.0.1

DB_PORT=3306

DB_DATABASE=here your database name

DB_USERNAME=here database username

DB_PASSWORD=here database password

Step 3: Install Laravel Passport

composer require laravel/passport

After successfully installing the package, we require to get default migration for creating new passport tables in our database. so let's run the bellow command.

php artisan migrate

Next, we need to install the passport using the command, Using passport:install command, it will create token keys for security. So let's run bellow command:

php artisan passport:install

Step 4: Add Client Table

php artisan make:model Client -m

database/migrations/2021_12_28_064135_create_clients_table.php

<?php

use Illuminate\Database\Migrations\Migration;

use Illuminate\Database\Schema\Blueprint;

use Illuminate\Support\Facades\Schema;

return new class extends Migration

{

/**

* Run the migrations.

*

* @return void

*/

public function up()

{

Schema::create('Clients', function (Blueprint $table) {

$table->id();

$table->string('name');

$table->string('email')->unique();

$table->string('password');

$table->timestamps();

});

}

/**

* Reverse the migrations.

*

* @return void

*/

public function down()

{

Schema::dropIfExists('Clients');

}

}

Use this command to run the migration.

php artisan migrate

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 arrays.

*

* @var array

*/

protected $hidden = [

'password',

'remember_token',

];

/**

* The attributes that should be cast to native types.

*

* @var array

*/

protected $casts = [

'email_verified_at' => 'datetime',

];

}

app/Models/Client.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;

use Illuminate\Database\Eloquent\Model;

use Illuminate\Foundation\Auth\User as Authenticatable;

use Illuminate\Notifications\Notifiable;

use Laravel\Passport\HasApiTokens;

class Client extends Authenticatable

{

use HasFactory, Notifiable, HasApiTokens;

/**

* The attributes that are mass assignable.

*

* @var array

*/

protected $fillable = [

'name', 'email', 'password',

];

}

Step 5: Add Passport in AuthServiceProvider

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 Type',

'client' => 'Client User Type',

]);

}

}

Step 6: Add Auth Guard

config/auth.php

// Add Guards

'guards' => [

'user' => [

'driver' => 'session',

'provider' => 'users',

],

'user-api' => [

'driver' => 'token',

'provider' => 'users',

],

'client' => [

'driver' => 'session',

'provider' => 'clients',

],

'client-api' => [

'driver' => 'token',

'provider' => 'clients',

],

],

// Add Provider

'providers' => [

'users' => [

'driver' => 'eloquent',

'model' => App\Models\User::class,

],

'clients' => [

'driver' => 'eloquent',

'model' => App\Models\Client::class,

],

],

Step 7: Add Scope Middleware

app/Http/Kernel.php

<?php

/**

* The application's route middleware.

*

* These middleware may be assigned to groups or used individually.

*

* @var array

*/

protected $routeMiddleware = [

'scopes' => \Laravel\Passport\Http\Middleware\CheckScopes::class,

'scope' => \Laravel\Passport\Http\Middleware\CheckForAnyScope::class,

];

Step 8: Add Route

routes/api/client.php

<?php

use Illuminate\Http\Request;

use Illuminate\Support\Facades\Route;

use App\Http\Controllers\LoginController;

/*

|--------------------------------------------------------------------------

| 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('client/login',[LoginController::class, 'clientLogin'])->name('clientLogin');

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

// authenticated staff routes here

Route::get('dashboard',[LoginController::class, 'clientDashboard']);

});

routes/api/user.php

<?php

use Illuminate\Http\Request;

use Illuminate\Support\Facades\Route;

use App\Http\Controllers\LoginController;

/*

|--------------------------------------------------------------------------

| 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('user/login',[LoginController::class, 'userLogin'])->name('userLogin');

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

// authenticated staff routes here

Route::get('dashboard',[LoginController::class, 'userDashboard']);

});

Step 9: Register Routes File In RouteServiceProvider

app/Http/Controllers/LoginController.php

$this->routes(function () {

Route::prefix('api')

->middleware('api')

->namespace($this->namespace)

->group(base_path('routes/api/client.php'));

Route::prefix('api')

->middleware('api')

->namespace($this->namespace)

->group(base_path('routes/api/user.php'));

});

Step 10: Add Controller

php artisan make:controller LoginController

app/Http/Controllers/LoginController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Models\User;

use App\Models\Client;

use Hash;

use Validator;

use Auth;

class LoginController extends Controller

{

/**

* Write code on Method

*

* @return response()

*/

public function userDashboard()

{

$users = User::all();

$success = $users;

return response()->json($success, 200);

}

/**

* Write code on Method

*

* @return response()

*/

public function clientDashboard()

{

$users = Client::all();

$success = $users;

return response()->json($success, 200);

}

/**

* Write code on Method

*

* @return response()

*/

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']);

$user = User::select('users.*')->find(auth()->guard('user')->user()->id);

$success = $user;

$success['token'] = $user->createToken('MyApp',['user'])->accessToken;

return response()->json($success, 200);

}else{

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

}

}

/**

* Write code on Method

*

* @return response()

*/

public function clientLogin(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('client')->attempt(['email' => request('email'), 'password' => request('password')])){

config(['auth.guards.api.provider' => 'client']);

$client = client::select('clients.*')->find(auth()->guard('client')->user()->id);

$success = $client;

$success['token'] = $client->createToken('MyApp',['client'])->accessToken;

return response()->json($success, 200);

}else{

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

}

}

}

Run Laravel App:

All steps have been done, now you have to type the given command and hit enter to run the Laravel app:

php artisan serve

Now, you have to open the web browser, type the given URL and view the app output:

// User Login

localhost:8000/user/login

// User Dashboard

localhost:8000/user/dashboard

// Client Login

localhost:8000/client/login

// Client Dashboard

localhost:8000/Client/dashboard

make sure in details API we will use the following headers as listed below:

'headers' => [

'Accept' => 'application/json',

'Authorization' => 'Bearer '.$accessToken,

]

I hope it can help you...

#Laravel 10