首頁  >  問答  >  主體

Laravel 中間件無法辨識使用者已登入

我正在使用Laravel 8,我想應用一個中間件來檢查使用者是否將is_staffis_superuser 設定為1,然後他可以存取管理儀表板,否則他無法訪問它。

為了做到這一點,我創建了這個:

public function handle($request, Closure $next)
    {
        if(Auth::check()) {
            if(auth()->user()->isSuperUser() || $request->user()->isStaffUser()) {
                return $next($request);
            }else{
                return redirect('/home');
            }
        }else{
            return redirect('/');
        }
    }

現在的問題是它返回 redirect('/'); 意味著中間件無法識別用戶已經登錄,但他已經登入了。

我已經這樣註冊了中間件:

protected $routeMiddleware = [
...
'auth.admin' => \App\Http\Middleware\AdminAuthenticated::class,

並將其套用到我的管理路由(RouteServiceProvider.php):

public function boot()
    {
        $this->configureRateLimiting();

        $this->routes(function () {
            ...

            Route::middleware('auth.admin')
                ->namespace($this->namespace)
                ->prefix('admin')
                ->group(base_path('routes/web/admin.php'));
        });
    }

這是 admin.php 路由:

Route::get('/',function (){
    return view('admin.master');
});

那麼這裡出了什麼問題呢?我該如何解決這個問題?

P粉935883292P粉935883292181 天前272

全部回覆(2)我來回復

  • P粉354602955

    P粉3546029552024-03-26 21:14:39

    您沒有顯示整個路由,但我敢打賭您的使用永遠不會被記錄。

    您可能會申請:

    Route::middleware('auth.admin')
                    ->namespace($this->namespace)
                    ->prefix('admin')
                    ->group(base_path('routes/web/admin.php'));

    對於所有管理路由。因此,您有登入表單,當您填寫登入資料時,使用者會點擊某個也應用此中間件的端點,因此它永遠不會到達您實際登入使用者的控制器,因為中間件重新導向回 /。

    除了登入/提醒密碼之外的所有路由都應該套用中間件,否則無法登入。

    回覆
    0
  • P粉797004644

    P粉7970046442024-03-26 20:56:59

    我認為您還需要將 web 中間件新增到管理路由。

    public function boot()
    {
        $this->configureRateLimiting();
    
        $this->routes(function () {
                ...
            Route::middleware(['web', 'auth.admin'])
                ->namespace($this->namespace)
                ->prefix('admin')
                ->group(base_path('routes/web/admin.php'));
        });
    }
    

    Auth::check() 嘗試從會話中取得目前登入的使用者。

    web 中間件群組啟動會話,它應用了一堆中間件

    //app/Http/Kernel.php
     'web' => [
         \App\Http\Middleware\EncryptCookies::class,            
         \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
         \Illuminate\Session\Middleware\StartSession::class,
         \Illuminate\View\Middleware\ShareErrorsFromSession::class,
         \App\Http\Middleware\VerifyCsrfToken::class,
         \Illuminate\Routing\Middleware\SubstituteBindings::class,
     ],
    

    沒有 web 中間件會話將不可用

    回覆
    0
  • 取消回覆