在所有控制器中检查用户的身份验证'行动

时间:2017-01-13 10:39:26

标签: php laravel authentication laravel-5

我使用Laravel 5.3,我遇到以下问题。

[UPDATE]

我最初的麻烦是当用户未登录系统时在网站上执行操作时出现错误。

启动浏览器时会发生这种情况,默认情况下会在页面上显示缓存信息。为登录用户显示的站点界面,而在他的系统中则没有。同时,产生一些动作,我得到一个用户未被授权的错误。

我的所有路线都有组认证中间件。当我重新启动站点的页面时,中间件被激活并重定向到登录页面。主要问题是浏览器显示缓存的信息。

因此,除了路由中间件之外,我还决定在控制器中进行身份验证。

[/ UPDATE]

我想在每个控制器的操作中检查用户的身份验证。在每个控制器中进行验证。手动操作不是解决方案,因为有许多控制器和操作。

所以我决定全球化。

由于所有控制器都扩展了主控制器(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);
}

这一切都很好,但我不喜欢这个解决方案,因为编辑核心文件并不好。

最后,我通过auth检查重新声明了主控制器中的callAction方法,但我也不喜欢这样。

有解决方案吗?

3 个答案:

答案 0 :(得分:1)

您应该使用middleware

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

或者:

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

或使用middleware groups

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

或使用controller's construct

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

答案 1 :(得分:0)

如果有一组路线,这将是最简单的方法

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

答案 2 :(得分:0)

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

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

点击此处:https://laravel.com/docs/5.3/authentication