Laravel 5.5 登台时需要身份验证

Laravel 5.5 require auth in staging

我有一个项目,其中包含一些包含路由的包。我有一个需要公开访问的 staging/demo 环境。

有没有办法为所有路由要求 auth 中间件(或类似的东西)而不将其放在所有单独的路由和路由组上? (在想什么bootstrap??)

如果您希望中间件在对您的应用程序的每个 HTTP 请求期间 运行,只需在 [=14] 的 $middleware 属性 中列出中间件 class =] class。

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,
];