Reputation: 563
I have set up an admin authentication guard as per described in this tutorial:
Laravel Multiple Auth Tutorial
Routes
Route::group([
'prefix' => 'admin',
'namespace' => 'Auth'
], function() {
Route::get('/login', 'AdminController@showLogin')->name('admin.show.login');
Route::post('/login', 'AdminController@login')->name('admin.login');
Route::group([
'middleware' => 'auth:admin'
], function() {
Route::get('/', 'AdminController@index')->name('admin.home');
Route::get('/logout', 'AdminController@logout');
});
});
Controller
class AdminController extends Controller
{
public function __construct()
{
$this->middleware('guest:admin')->except('logout');
}
public function index()
{
return "Admin authenticated";
}
public function showLogin()
{
return view('admin.login');
}
public function login(Request $request)
{
$admin = Admin::where('login_id', $request->input('login'))->firstOrFail();
Auth::guard('admin')->loginUsingId($admin->id, TRUE);
return redirect()->intended(route('admin.home'));
}
public function logout()
{
Auth::guard('admin')->logout();
return redirect()->route('admin.show.login');
}
}
RedirectIfAuthenticated
middleware
public function handle($request, Closure $next, $guard = null)
{
switch ($guard)
{
case 'admin':
if (Auth::guard($guard)->check())
{
return redirect()->route('admin.home');
}
break;
default:
if (Auth::guard($guard)->check()) {
return redirect('/home');
}
break;
}
return $next($request);
}
Exception handler
protected function unauthenticated($request, AuthenticationException $exception)
{
if ($request->expectsJson())
{
return response()->json(['error' => 'Unauthenticated.'], 401);
}
$guard = array_get($exception->guards(), 0);
switch ($guard)
{
case 'admin':
$login = 'admin.show.login';
break;
default:
$login = 'login';
break;
}
return redirect()->guest(route($login));
}
When /admin
is accessed without loggin in, the /admin/login
view is correctly. After logged in, the /admin
URL is casuing infinite redirect loop error. The admin can be successfully logged out using /admin/logout
route. The problem seems to be the cause of RedirectIfAuthenticated
middleware. Am I missing something?
Upvotes: 1
Views: 1219
Reputation: 4556
Seems that your problem happens in the AdminController
, specifically the constructor function.
The redirection loop happens on route /admin
because the middleware is conflicting with auth:admin
middleware (in the routes) and guest:admin
middleware (in the controller).
What you want is to apply the guest:admin
middleware to all except index
and logout
function:
$this->middleware('guest:admin', ['except' => ['index', 'logout']]);
Upvotes: 1