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

Apply Auth Middleware to All Laravel Routes

当我在所有控制器中应用 auth 中间件时,如何验证除登录和注册之外的所有路由的正确方法?有没有办法在一个地方应用auth中间件并排除登录,注册路由?

你可以在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
    });
});

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

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

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

以上路由名称只是编造的,请为您的路由和控制器遵循正确的命名约定。另请阅读 here and about routing over here

中的中间件

您可以将中间件添加到整个 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'));
}

这(不是?)完全不相关,但这是一个 示例,它是一种处理大量路由文件而不是将所有路由放入单个 [=14] 的简洁方法=] 文件:

创建新方法mapAdminRoutes():

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

映射它:

public function map()
{
    $this->mapWebRoutes();
    $this->mapAdminRoutes(); // <-- add this
    ...
}

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

<?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');

...

现在您可以在 1 个地方配置所有内容,例如 prefixnamemiddlewarenamespace

检查 php artisan route:list 以查看结果:)