PHP
laravel

LaravelでBasic認証を設定値で切り替える

More than 1 year has passed since last update.

LaravelのBasic認証を設定値で切り替えます。

独自のミドルウェアを作る

元のBasic認証のミドルウェアは

Illuminate/Auth/Middleware/AuthenticateWithBasicAuth.php

なのでこれを継承して独自のミドルウェアを作ることにします。

App/Http/Middleware/CustomAuthenticateWithBasicAuth.php
<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Auth\Middleware\AuthenticateWithBasicAuth;
use Illuminate\Contracts\Auth\Factory as AuthFactory;
use Illuminate\Contracts\Config\Repository as Config;

class CustomAuthenticateWithBasicAuth extends AuthenticateWithBasicAuth
{
    private $config;

    public function __construct(AuthFactory $auth, Config $config)
    {
        parent::__construct($auth);
        $this->config = $config;
    }

    public function handle($request, Closure $next, $guard = null)
    {
        if ($this->config->get('app.basic_auth')) {
            return parent::handle($request, $next, $guard);
        }

        return $next($request);
    }
}

設定の値を取得するためにコンストラクタで\Illuminate\Contracts\Config\Repositoryを受け取るようにしました。

$this->config->get('app.basic_auth')の値でbasic認証の親クラスに流すか、どうかを分岐します。

ミドルウェアを差し替える

app/Http/Kernel.php
<?php

namespace App\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel
{

・・・ 中略 ・・・

    /**
     * The application's route middleware.
     *
     * These middleware may be assigned to groups or used individually.
     *
     * @var array
     */
    protected $routeMiddleware = [
        'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
        'auth.basic' => \App\Http\Middleware\CustomAuthenticateWithBasicAuth::class,
        'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
        'can' => \Illuminate\Auth\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
    ];
}

auth.basicの部分をCustomAuthenticateWithBasicAuthに差し替えます。

設定値を追加

config/app.php
<?php

return [

     ・・・ 中略 ・・・

    /*
     |--------------------------------------------------------------------------
     | Basic Auth Configuration
     |--------------------------------------------------------------------------
     */

    'basic_auth' => env('BASIC_AUTH', false),

]
.env
BASIC_AUTH=true