4 回答

TA貢獻(xiàn)1856條經(jīng)驗(yàn) 獲得超5個(gè)贊
我一直在尋找基于守衛(wèi)的答案,我希望檢查守衛(wèi)而不是基于守衛(wèi)類型的重定向。但是我找不到解決方案。
然而,我找到了另一個(gè)可以完成工作的解決方案,但它并不像我正在尋找的答案那么動(dòng)態(tài)。然而,它對(duì)我來(lái)說(shuō)工作得很好
在
應(yīng)用\Http\Middleware\Authinticate.php
類中,添加以下代碼:
protected function redirectTo($request)
{
if (! $request->expectsJson()) {
if($request->is('admin') || $request->is('admin/*'))
return route('admin.login');
return route('login');
}
}
另外,不要忘記為所有管理路由添加前綴 admin/ 。希望這個(gè)答案對(duì)您有幫助。

TA貢獻(xiàn)1946條經(jīng)驗(yàn) 獲得超4個(gè)贊
轉(zhuǎn)到應(yīng)用程序/Exception/Handler.php
使用這個(gè)類
use Illuminate\Auth\AuthenticationException;
并在類中添加這個(gè)函數(shù)
protected function unauthenticated($request, AuthenticationException $exception)
{
if (request()->expectsJson()) {
return Response()->json(['error' => 'UnAuthorized'], 401); //exeption for api
}
$guard = data_get($exception->guards(), 0);
switch ($guard) {
case 'admin':
$login = 'admin.login';
break;
default:
$login = 'login';
break;
}
return redirect()->guest(route($login));
}

TA貢獻(xiàn)1828條經(jīng)驗(yàn) 獲得超3個(gè)贊
我不確定這是否是正確的方法,我重寫了handle方法,這樣我就可以從中獲取守衛(wèi),如下所示:
protected $guards = [];
public function handle($request, Closure $next, ...$guards)
{
$this->guards = $guards;
return parent::handle($request, $next, ...$guards);
}
protected function redirectTo($request)
{
if (in_array("admin", $this->guards)) {
return "admin/login";
}
}

TA貢獻(xiàn)1775條經(jīng)驗(yàn) 獲得超8個(gè)贊
好的,我已經(jīng)解決了,我想這是一個(gè)很好的方法。我創(chuàng)建了一個(gè)中間件,并要求中間件上的身份驗(yàn)證防護(hù)。
首先我創(chuàng)建中間件
class IsAdmin
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if (Auth::guard('admin')->check())
return $next($request);
else
return redirect('/admin/login');
}
}
然后我將中間件放入內(nèi)核文件中
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'isAdmin' => \App\Http\Middleware\IsAdmin::class,
最后,我更改了路由的中間件
Route::get('/admin', 'AdminController@index')->name('admin');
現(xiàn)在它工作正常,但如果你有更好的解決方案,我真的很想知道。
- 4 回答
- 0 關(guān)注
- 237 瀏覽
添加回答
舉報(bào)