Laravel 5.5需要auth进行分段

时间:2017-09-12 11:44:35

标签: php routes laravel-middleware laravel-5.5

我有一个包含几个包含路径的包的项目。我有一个需要公开访问的登台/演示环境。

是否有办法要求所有路由的auth中间件(或类似的东西),而不是将它放在所有单独的路由和路由组上? (在bootstrap中思考什么?)

1 个答案:

答案 0 :(得分:4)

如果您希望在对应用程序的每个HTTP请求期间运行中间件,只需在$middleware类的app/Http/Kernel.php属性中列出中间件类。

protected $middleware = [
    \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
    \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
    \App\Http\Middleware\TrimStrings::class,
    \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
    \App\Http\Middleware\TrustProxies::class,
    YOUR MIDDLEWARE::class,
];

如果您无权访问或不想修改软件包控制器,则可以创建中间件(建议继承自AuthenticateSession。例如:

<?php

namespace App\Http\Middleware;

use Illuminate\Session\Middleware\AuthenticateSession;

use Auth;
use Closure;

class AuthenticateIfEnvironment extends AuthenticateSession
{
    public function handle($request, Closure $next)
    {
        if (env('APP_ENV') == 'XXXXXXXX' && !Auth::user() && !$request->is('login')) {
            return redirect('/login');
        }
        return parent::handle($request, $next);
    }
}

然后Kernal.php看起来像这样:

protected $middleware = [
    \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
    \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
    \App\Http\Middleware\TrimStrings::class,
    \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
    \App\Http\Middleware\TrustProxies::class,
    \App\Http\Middleware\AuthenticateIfEnvironment::class,
];