如何在 Laravel Horizon 加上 Basic Auth?

如果你希望在 Production 正式環境上查看 Horizon,那麼你可以在 Horizon 的路由上加上一個中間層 Middleware 來做驗證。這邊提供一個使用 Basic Auth 的驗證方式:

第一步:在 /configs/horizon.php 裏設定登入用的帳號密碼

'authorized_identities' => [
    ['youraccount', 'yourpassword']
],

第二步:建立 Basic Auth Middleware

<?php

namespace App\Http\Middleware;

use Closure;

class HorizonAuthBasic
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if (!collect(config('horizon.authorized_identities'))
            ->contains([$request->getUser(),$request->getPassword()])) {
            $headers = array('WWW-Authenticate' => 'Basic');
            return response('Unauthorized', 401, $headers);
        }

        return $next($request);
    }
}

第三步:在 /app/Http/Kernel.php 裏註冊 Middleware

protected $routeMiddleware = [
   // ....
   'horizon.auth' => \App\Http\Middleware\HorizonAuthBasic::class,
];

第四步:將 Middleware 加入到 /configs/horizon.php 設定

'middleware' => ['web', 'horizon.auth'],

第五步:修改 /app/Providers/HorizonServiceProvider.php 設定 Horizon 可在 Production 環境瀏覽

    protected function authorization()
    {
        $this->gate();
    }

    protected function gate()
    {
        Gate::define('viewHorizon', function ($user = null) {
            return true;
        });
    }