PHP Classes

How to use Laravel Multi Auth Guard in Laravel 5.8

Recommend this page to a friend!
  Blog PHP Classes blog   RSS 1.0 feed RSS 2.0 feed   Blog How to use Laravel Mu...   Post a comment Post a comment   See comments See comments (3)   Trackbacks (0)  

Author:

Viewers: 1,648

Last month viewers: 231

Categories: PHP Security

Laravel is a popular Web framework that provides tools that can generate code for complex tasks such as authentication users.

You can use different methods of authentication of your choice but if for some reason you want to use more than one method of authentication, you can use the Laravel Multi Auth Guard support.

Read this article to learn how you can implement Multi Auth Guard support in your Laravel Web applications.




Loaded Article

Introduction to Laravel Authentication Support

As we all know, user authentication can be achieved with Laravel in jiffy way, that is, run php artisan make:auth and you will get controllers, blade views all ready to launch with authentication.

But here is the catch. Laravel provides default authentication on User model or users table. What if there are two types of users completely different to each other, for example application users and admins ?

One thing we can do is, make a column in users table with name as type and there we define type of user, 1 for admin and 0 for normal user. This method is completely wrong, do not do this ever. Period.

Keep normal users in user table and for admins create another table as admin. Laravel ships a default authentication guard called web which is applied on User model. For instance go to config/auth.php

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

What is a Guard in Laravel Authentication?

A guard is a way of supplying the logic that is used to identify authenticated users. Laravel provides different guards like sessions and tokens. For this article, I am just talking about session guard which is web by default.

Here is a sample of config/auth.php file to demonstrate how to configure Laravel guards.

config/auth.php

'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],
        'api' => [
            'driver' => 'token',
            'provider' => 'users',
            'hash' => false,
        ]
],
'providers' => [
        'users' => [
            'driver' => 'eloquent',
            'model' => App\User::class,
        ]
],

As you can see, the default authentication guard web is applied on User model.

How to Create a Guard in Laravel?

As I said above, you can make another table and model for admin users, admin table and Admin model respectively using following commands:

php artisan make:migration create_admins_table

And for Admin model:

php artisan make:model Models/Admin

You can copy the database schema of users table to admins table from database/migrations/<timestamp>_create_users_table.php or you can add your custom schema too.

Edit config/auth.php

Add following in guards array:

'admin' => [
            'driver' => 'session',
            'provider' => 'admins',
        ],

And in providers array:

'admins' => [
            'driver' => 'eloquent',
            'model' => App\Models\Admin::class,
        ],

How to Create Middleware for Normal Users and Admin Users Routes

What is Middleware in Laravel?

A middleware is a piece of code which is executed before a particular route hits a controller method.

Basically a middleware is used for authentication purposes, so that protected routes/endpoints should not be hit by any outside user or application, once a request is authenticated its control is passed next to the controller method.

Now create 2 middlewares for routes which belong to normal users and admin users respectively.

php artisan make:middleware AuthUsers
php artisan make:middleware AuthAdmins

Above commands will create 2 files in app/Http/Middleware directory

AuthUsers middleware

<?php
namespace App\Http\Middleware;
use Closure;
use Auth;
use Illuminate\Support\Facades\Session;
class AdminUsers
{
    /**
    * Handle an incoming request.
    *
    * @param  \Illuminate\Http\Request $request
    * @param  \Closure $next
    * @return mixed
    */
    public function handle($request, Closure $next)
    {
        if (false == Auth::check()) {
            return redirect()->route('view.login); //redirect User to login page
        }
        return $next($request);
    }
}

AuthAdmins middleware

<?php

namespace App\Http\Middleware;

use Closure;
use Auth;
use Illuminate\Support\Facades\Session;

class AdminAuth
{
    /**
    * Handle an incoming request.
    *
    * @param  \Illuminate\Http\Request $request
    * @param  \Closure $next
    * @return mixed
    */
    public function handle($request, Closure $next)
    {
        if (false == Auth::guard('admin')->check()) {
            return redirect()->route('view.login.admin');
        }

        return $next($request);
    }
}

In this middleware, I am telling laravel to use admin guard on this middleware and check() if admin is logged in otherwise redirect the request to login route and then route will load login view for the admin.

Register Middlewares in Kernel.php

Now it is time to register these two middlewares in Kernel.php . Here you need to be careful as there are 2 Kernel.php in laravel one is at app/Console directory and other one is at app/Http directory. We need to take the later one which is app/Http/Kernel.php for middleware registrations.

Add the following 2 lines in protected $routedMiddleware array:

protected $routeMiddleware = [
        'auth.user => \App\Http\Middleware\AuthUsers::class,
        'auth.admin' => \App\Http\Middleware\AuthAdmins::class,
];

Apply Each Middleware on their Respective Routes in web.php

For authenticated users:

Route::group(['middleware' => ['auth.user]], function () {
    // login protected routes.
});

For authenticated admin users:

Route::group(['middleware' => ['auth.admin]], function () {
    // login protected routes.
});

Conclusion

So friends, it was all about guards and middlewares in Laravel. I hope you enjoyed this tutorial and helped you. Please share this post with your friends on facebook, twitter as a good gesture for me to keep posting interesting topics.

Thank You !

Source:  Tumblr




You need to be a registered user or login to post a comment

1,616,683 PHP developers registered to the PHP Classes site.
Be One of Us!

Login Immediately with your account on:



Comments:

1. Why should normal user model never be used with admins? - Pjotr (2019-12-05 23:27)
Need an explanation why not to use normal model for admins... - 2 replies
Read the whole comment and replies



  Blog PHP Classes blog   RSS 1.0 feed RSS 2.0 feed   Blog How to use Laravel Mu...   Post a comment Post a comment   See comments See comments (3)   Trackbacks (0)