Laravel 5.1:全局使用默认的Auth中间件

时间:2015-12-02 20:30:50

标签: laravel authentication laravel-5.1 middleware

我正在尝试全局使用开箱即用的Authenticate中间件,除了auth/loginauth/logout,因此我不需要在每个控制器中添加它。我将它添加到Kernel中的全局中间件列表中(如下所示);然而,它陷入无限auth/login重定向。对于任何访客,我希望将页面重定向到auth/login并留在那里。

class Kernel extends HttpKernel
{
    protected $middleware = [
        ...
        \App\Http\Middleware\Authenticate::class,
    ];
}

这种情况正在发生,因为第一次点击auth/login时,全局Authenticate会一次又一次地重新定向到auth/login

是否可以像我所描述的那样全局使用默认的Authenticate中间件?我需要为它创建一个新的中间件吗?

编辑:我的结论是托马斯的做法已经足够好了。

1 个答案:

答案 0 :(得分:3)

您始终可以使用Route Groups。在routes.php文件中......

// Your login/logout routes
Route::get('login', 'Auth\AuthController@getLogin');
Route::post('login', 'Auth\AuthController@postLogin');
Route::get('logout', 'Auth\AuthController@getLogout');

Route::group(['middleware' => 'auth'], function() {
    // Put all other routes here and the auth middleware will be applied on them all
});

编辑:此外,您不需要将Authenticate中间件添加到全局中间件堆栈。只需将其保留为默认$routeMiddleware

'auth' => \App\Http\Middleware\Authenticate::class,