簡體   English   中英

在所有控制器的操作中檢查用戶的身份驗證

[英]Check the user's auth in all controllers' actions

我使用Laravel 5.3,但遇到以下問題。

[更新]

我最初的麻煩是,當用戶未登錄系統時,在站點上執行操作時出現錯誤。

啟動瀏覽器時會發生這種情況,默認情況下,頁面上會顯示緩存的信息。 為登錄的用戶顯示站點界面,而在其系統中則沒有。 同時,執行一些操作,我得到一個錯誤,表明用戶未被授權。

我的所有路由都具有組身份驗證中間件。 當我重新啟動站點頁面時,中間件被激活並將我重定向到登錄頁面。 主要問題是瀏覽器顯示了緩存的信息。

因此,除了路由的中間件之外,我還決定在控制器中進行身份驗證檢查。

[/更新]

我想在每個控制器的操作中檢查用戶的身份驗證。 手動對每個控制器的動作進行auth檢查不是一個解決方案,因為存在許多控制器和動作。

因此,我決定在全球范圍內推廣。

由於所有控制器都擴展了主控制器(App \\ Http \\ Controllers \\ Controller.php),因此我決定在構造函數中編寫auth()-> check():

function __construct()
{
    if(auth()->check()) dd('success');
}

但是...什么也沒發生(((((然后我在BaseController中找到了主控制器擴展的callAction方法,並在此處進行了檢查:

public function callAction($method, $parameters)
{
    if(auth()->check()) dd('success');
    return call_user_func_array([$this, $method], $parameters);
}

這次一切正常,但是我不喜歡這種解決方案,因為編輯核心文件不是很好。

最后,我通過身份驗證檢查在主控制器中重新聲明了callAction方法,但我也不喜歡這種方式。

有什么辦法嗎?

您應該使用中間件

Route::get('profile', ['middleware' => 'auth', 'uses' => 'UserController@showProfile']);

要么:

Route::get('profile', 'UserController@show')->middleware('auth');

或使用中間件組

Route::group(['middleware' => ['auth']], function () {
    // Controllers here.
});

或使用控制器的構造

public function __construct()
{
    $this->middleware('auth');
}

如果有一組路線,這將是最簡單的方法

Route::group(['middleware' => ['auth']], function()
{
    // here all of the routes that requires auth to be checked like this
    Route::resource('user','UsersController');
}

另一種方式

function __construct()
{
    $this->middleware('auth');
}

在控制器路由上指定了另一種方法

Route::get('profile', [
    'middleware' => 'auth',
    'uses' => 'UserController@showProfile'
]);

請參閱文件

https://laravel.com/docs/5.0/controllers#controller-middleware

您可以在控制器中使用auth中間件

public function __construct()
{
   $this->middleware('auth');
}

在這里檢查: https : //laravel.com/docs/5.3/authentication

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM