将 Auth 中间件应用于所有 Laravel 路由

use*_*236 5 laravel laravel-routing laravel-5 laravel-middleware

当我在所有控制器中应用身份验证中间件时,除了登录和注册之外,对所有路由进行身份验证的正确方法是什么?有没有办法在一个地方应用身份验证中间件并排除登录、注册路由?

emo*_*ity 8

您可以web.php通过将中间件添加到 中的路由映射来将中间件添加到整个路由文件中RouteServiceProvider

转到app/Providers/RouteServiceProvider.php并在 中mapWebRoutes(),更改middleware('web')middleware(['web', 'auth'])

protected function mapWebRoutes()
{
    Route::middleware(['web', 'auth'])
         ->namespace($this->namespace)
         ->group(base_path('routes/web.php'));
}
Run Code Online (Sandbox Code Playgroud)

这是(不是?)完全不相关的,但这里有一个处理大量路由文件的干净方法的示例web.php,而不是将所有路由放入单个文件中:

创建一个新方法mapAdminRoutes()

protected function mapAdminRoutes()
{
    Route::middleware(['web', 'auth:admin'])
        ->namespace('App\Http\Controllers\Admin')
        ->name('admin.')
        ->group(base_path('routes/admin.php'));
}
Run Code Online (Sandbox Code Playgroud)

映射它:

public function map()
{
    $this->mapWebRoutes();
    $this->mapAdminRoutes(); // <-- add this
    ...
}
Run Code Online (Sandbox Code Playgroud)

在您的文件夹中创建一个admin.php文件routes,然后为管理员创建路由:

<?php

use Illuminate\Support\Facades\Route;

// This route's name will be 'admin.dashboard'
Route::get('dashboard', 'DashboardController@dashboard')->name('dashboard');

// This route's name will be 'admin.example'
Route::get('example', 'ExampleController@example')->name('example');

...
Run Code Online (Sandbox Code Playgroud)

现在您可以在 1 个位置配置所有内容,例如prefixname和。middlewarenamespace

检查php artisan route:list一下结果:)


Dje*_*iss 7

你可以在routes.php文件中应用中间件,你需要做的是将所有路由放在一个组中,并添加中间件'auth'(除了已经配置的Auth::routes()),例如:

Route::middleware(['first', 'second'])->group(function () {
    Route::get('/', function () {
        // Uses first & second Middleware
    });

    Route::get('user/profile', function () {
        // Uses first & second Middleware
    });
});
Run Code Online (Sandbox Code Playgroud)

更多信息可以在文档中找到:https://laravel.com/docs/5.7/routing#route-group-middleware


Kha*_*ukh 6

您可以将所有经过身份验证的路由分组如下,laravel 为 auth 和来宾用户提供默认中间件

Route::group(['middleware' => ['auth']], function () { 
    Route::get('home', 'HomeController@index');
    Route::post('save-user', 'UserController@saveUser');
    Route::put('edit-user', 'UserController@editUser');
});
Run Code Online (Sandbox Code Playgroud)

上面的路由名称只是组成,请遵循适当的路由和控制器命名约定。还可以阅读有关中间件在这里和有关路由在这里