JavedBaloch's avatar

Authentication issue with Admin & Front

Hello all,

I am working on an application which contains its front end and admin panel How do I implement separate authentication for them?

Let's say for ex. Front-end authentication is working fine I'm using the standard auth()->attempt() but what about admin panel I think I can not use the same for the admin panel, once if I logged in from front-end then if I check dd(auth()->user()) in admin area somewhere but it returns the front end users data.

In short, I have been stuck in two Authentication can someone tell me the logic "How do I implement two separate authentication one for admin panel and for front end"

Thanks

0 likes
6 replies
martinbean's avatar

@muhammadjaved A user is a user. Once authenticated, you should check they’re permissions to see if they can access the admin panel etc.

The Laravel documentation has a section on authorization: https://laravel.com/docs/master/authorization.

You could add middleware that you apply to your admin routes to check if your user is an administrator, and then policies to check the user’s permissions for each part of your admin panel.

1 like
JavedBaloch's avatar

Hello, @martinbean, Basically, I don't need users to log in to the admin panel.

I need separate authentication for administrators.

martinbean's avatar

@muhammadjaved Why? An administrator is just a user with privileges. There’s no need to create a separate user model, controllers, views, auth guard etc.

What happens if you then need to add a third user type, say a moderator? Are you then going to create a third user model, controllers etc?

JavedBaloch's avatar

@martinbean you mean you can the users which get register from Frontend/Home we should also mix them with administrators sorry I couldn't understand

Helmchen's avatar

you can use 2 different guards with 2 different models if you want

in your config/auth.php

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

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

then just provide the right guard as suffix to your middlewares:

$this->middleware('auth:admin');

Auth::guard('admin')->check()

// and so on

You have to tweak the Login Controller for the Backend to use the right guard, but that is totally doable :)

1 like

Please or to participate in this conversation.