Laravel - Authentication issue with Admin & Front - laravel

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

if you are using laravel inbuilt authentication method, you can use custom guards
In your auth.php file add custom guard
'guards' => [
'admin' => [
'driver' => 'session',
'provider' => 'users',
],
'customer' => [
'driver' => 'session',
'provider' => 'customers',
],
]
and access by
Auth::guard('customer')->attempt() function.
for more details https://laravel.com/docs/5.6/authentication#adding-custom-guards

Related

LARAVEL: Multiple drivers for one auth guard

I am trying to figure out to provide multiple ways of authentication for the API service within my Laravel app. The app is a SPA using Vue.js and uses the API route to render and present all the view components. Currently, I am using a JWT driver for the API guard within the application. However, I'd also like to offer my clients the ability to access the same API via OAuth and Laravel's personal API token. With that being said, how do I protect my resources with the Auth middleware where it can be accessed internally with a JWT or externally by a client with OAuth or an API Token.
Controller:
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
// Make sure user is authenticated
$this->middleware('auth:api');
//$this->middleware('auth:oauth');
}
Auth Guards:
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'jwt',
'provider' => 'users',
],
'oauth' => [
'driver' => 'token',
'provider' => 'users',
]
],
If you want to be able allow multiple guards for your routes you can supply the different guards to the middleware call, like you have done already with the api guard, except you supply them as comma separated values:
$this->middleware('auth:api,oauth,web');
This will mean that if a user has been authenticated with one of the guards they will be able to access the route(s).

Need to let users login with multiple credentials same as login with other account functionality in Gmail services- Laravel

I want to let my users to login with different credentials in the same browser window, which is using the single users table. If tables were different then I will surely do that with guards, but the problem is I have to manage the user logins through single table.
Please help me how to manage multiple sessions in the same browser window, as when I login with other account in a new tab the first one goes logout.
Thanks in advance.
What I wanted to do was to maintain multiple session for a user, so he can log in with his other email-ids inside the same browser window in different tabs.
Here we go, how we can manage that and how Gmail is managing it.
At first you have to manage that, the user want to login with his other account or switch accounts. So you can show him the login page by appending any notation in url that shows he want to switch accounts.
If your original login URL is http://www.examle.com/login
then for multiple login, you can give him URL like http://www.examle.com/u/1/login (you can increase the number after u/ part as many times you want to switch accounts)
Then go to your config/sessions.php and edit your cookie part as follows
<?php
$user_type = ( ( !empty(request()) && (int)request()->segment(2) ) > 0 ? '_'. request()->segment(2) : '');
return [
//.....rest of array
'cookie' => env(
'SESSION_COOKIE',
Str::slug(env('APP_NAME', 'laravel'), '_').'_session'. $user_type //This user_type generate various session keys for your multiple login according to generated URL
),
];
Then you have to change your all URL's as dynamic so that it can execute for both your normal route(without '/u/number/url' part) and with the /u/number/url part.
Define the following variable at the top of your web.php
/**
* Setting a variable to check if the user is logging in with first or multiple sessions
*/
$user_login = ( (int)request()->segment(2) > 0 ? 'u/'. request()->segment(2) : '' );
/**
* User attempting to login with other accounts
*/
Route::post($user_login. '/login', 'Auth\LoginController#login');
/**
* Get dashboard for filling the registeration forms
* Your entire app URL will now go like this, whether you can use it with user number or without it. It will go smoothly
*/
Route::get($user_login. '/dashboard', ['as' => 'dashboard', 'uses' => 'FormController#getDashboard']);
/**
* User attempting to login with other accounts
*/
Route::post($user_login. '/logout', 'Auth\LoginController#logout');
This works great. Thanks everyone for the help.
Create a new guard in admin auth with same model.
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\Models\User::class,
],
'clients' => [
'driver' => 'eloquent',
'model' => App\Models\User::class,
],
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'front' => [
'driver' => 'session',
'provider' => 'clients',
],
In the controller:
if ($this->guard()->attempt(['email' => $request->email, 'password' => $request->password, 'active' => 1])) {
dd(' i am logged in');
}
}
protected function guard()
{
return auth()->guard('front');
}

how to create multi auth in one single login form

I want to create an authentication system (one single form) that gives the ability to admin and student to access tow different interfaces the admin can access the control panel and the user access the main system. in addition, I want separate tables in the database one for the admin and the other for the student. is there a possible way to do this? any suggestions please and how to do it.
Thank you...
You need to change redirectifauthenticated.php file in middleware folder.
I can edit my answer later, i can't access my codes right now. But this idea will work:
In the handle function:
switch ($guard){
case 'admin':
if (Auth::guard($guard)->check()){
//if you are using some role package, use with auth()->user()->hasrole('admin'), depends //your package
return redirect()->route('adminurl');
}
break;
default:
if (Auth::guard($guard)->check()){
return redirect('/homepage');
}
break;
}
return $next($request);
In config/auth.php also you need to add admin guard to the guards section. Also same thing for providers.
this for providers:
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
'admins' => [
'driver' => 'eloquent',
'model' => App\AdminModel::class,
],
]

Laravel: How to use Gates with multiple Guards

I have a traditional web application that has a number of different user types, and each user type has its own Authentication guard.
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'admin' => [
'driver' => 'session',
'provider' => 'admin',
],
'timekeeper' => [
'driver' => 'session',
'provider' => 'timekeeper',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
],
],
Most my users authenticate using the 'web' guard, however administrators and timekeepers each use their own guard, which is attached to an appropriate user provider.
This is fine until I try to use authentication gates. If I authenticate a user against the system's default guard (e.g. 'web'), then the gates work as expected. If I authenticate against any other guard however, then all Gate::allows(...) calls are DENIED.
Even the following ability is denied:
Gate::define('read', function ($user) {
return true;
});
Presumably this is due to line 284-286 in Illuminate\Auth\Access\Gate:
if (! $user = $this->resolveUser()) {
return false;
}
As far as I can see, my options are to:
Go back to using a single 'web' guard, with a user provider that can locate any type of user (but I'm not sure how that would work if I start using an API in parallel)
Somehow set the default guard at run time, depending on the type of the current user. (It is currently set in the config file)
Somehow inject a different user resolver in to the Gate facade (again, depending on the type of the current user)
None of these seems intuitive however. Am I missing something?
It's not the most elegant solution because it requires a lot of extra boilerplate code, but you can use Gate::forUser($user)->allows() instead of just Gate::allows() where $user comes from Auth::guard().
I had the same problem and I didn't really like this solution. After quite a lot of research I came up with this way to make your own user resolver in the Gate:
public function register()
{
$this->app->singleton(GateContract::class, function ($app) {
return new \Illuminate\Auth\Access\Gate($app, function () use($app) {
$user = call_user_func($app['auth']->userResolver());
if (is_null($user)) {
// Implement your own logic for resolving the user
}
return $user;
});
});
}
I put this in my AuthServiceProvider.

Yii2 Advanced app, different sessions for frontend and backend

I'm trying to set up a Yii2 advanced project. For this I used kartik-v's advanced app template. It works fine but (as He just mentioned here) if you log into the frontend and then go to backend you'll be logged in as well. So I would like to separate the frontend and backend logins (different sessions). I tried to configure the identity cookies but It didn't work. In the comments I found this: "Still, when either frontend or backend is signed in and we open the other, it shows automatically signed in because the session cookie is same, PHPSESSID."
So I changed the name and the savePath of the sessions in the config of frontend and the backend. With this it should work, but It doesnt. I got an 500 internal server error every time I go to my page. And if I try to log in, it just doesnt work, it redirects me but does not log me in. I found out that If I dont set the savePath I dont get the error but still nothing happens. And If check in the 'remember me' option I get the error message but the login works.. So I dont know what to do now. My main config files:
backend:
'components' => [
'session' => [
'name' => 'backend_sessid',
'savePath' => __DIR__ . '/../tmp',
],
'user' => [
'identityClass' => 'common\models\User',
'enableAutoLogin' => true,
'identityCookie' => [
'name' => '_backendUser',
'path' => '/projectname/backend/web'
]
],
frontend:
'components' => [
'session' => [
'name' => 'frontend_sessid',
'savePath' => __DIR__ . '/../tmp',
],
'user' => [
'identityClass' => 'common\models\User',
'enableAutoLogin' => true,
'identityCookie' => [
'name' => '_frontendUser',
'path' => '/projectname'
]
],
One approach would be to use the Role Based Access Control described here: http://www.yiiframework.com/doc-2.0/guide-security-authorization.html
This way, you would set different roles for frontend users and backend users. If a user with different privileges tried to access the wrong site area, you could log him out and redirect him to the login page.

Resources