I have a multiple authentication system set up in Laravel 5.7
There is an 'admin' section of the site and a 'learner' section of the site. When you try to access a portion of either site, it redirects you the correct login page if you're not logged in yet.
However, if follow these steps, I come across an issue with the redirects:
It properly logs me in, but improperly redirects to the other login page. The issue also happens vice versa, if I get an automatic redirect to the 'learner' then link directly to the admin login page and log in.
I believe I've narrowed the issue down to the unaunthenticated function I've placed in the Exception/Handler.php file, but I can't figure out where to go from there.
protected function unauthenticated($request, AuthenticationException $exception)
{
if ($request->expectsJson()) {
return response()->json(['error' => 'Unauthenticated.'], 401);
}
$guard = array_get($exception->guards(), 0);
switch ($guard) {
case 'learner':
$login = 'learner.login';
break;
default:
$login = 'login';
break;
}
return redirect()->guest(route($login));
}
Using each separate login page works fine. It's just when you follow the process above that I see issues.
I use separate middleware in each controller like this:
Admin Home Controller
public function __construct()
{
$this->middleware('auth');
}
Admin login controller:
public function __construct()
{
$this->middleware('guest')->except('logout');
}
Learner home controller
public function __construct()
{
$this->middleware('auth:learner');
}
Learner login Controller:
public function __construct()
{
$this->middleware('guest:learner')->except('logout');
}
Solution: Clearing out the intended url with Session:forget('url.intended');
protected function unauthenticated($request, AuthenticationException $exception)
{
// dd($exception);
if ($request->expectsJson()) {
return response()->json(['error' => 'Unauthenticated.'], 401);
}
$guard = array_get($exception->guards(), 0);
switch ($guard) {
case 'learner':
$login = 'learner.login';
break;
default:
$login = 'login';
break;
}
Session::forget('url.intented');
return redirect()->route($login);
}
Solution: Clearing out the intended url with Session:forget('url.intended');
protected function unauthenticated($request, AuthenticationException $exception)
{
// dd($exception);
if ($request->expectsJson()) {
return response()->json(['error' => 'Unauthenticated.'], 401);
}
$guard = array_get($exception->guards(), 0);
switch ($guard) {
case 'learner':
$login = 'learner.login';
break;
default:
$login = 'login';
break;
}
Session::forget('url.intented');
return redirect()->route($login);
}