LoginSignup
1
0

More than 5 years have passed since last update.

Heroku上のLaravel AppにIP制限をかける

Posted at

手順

  • \App\Http\Middleware\IPAuthMiddleware を作成
  • \App\Http\Kernel に登録
  • Herokuの Config Variables にIPアドレスをカンマ区切りで追加

ポイント

  • Heroku上のAppではIPアドレスを取得するときは先に setTrustedProxies を通す
IPAuthMiddleware.php
<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Response;

class IPAuthMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $isPrd = !$this->isDebug();
        $isDenied = !$this->whetherThisIpAccepted();
        if ($isPrd && $isDenied) {
            return Response::create(view("errors.403"), 403);
        }
        return $next($request);
    }

    protected function isDebug()
    {
        if (env('APP_DEBUG') !==  true) {
            return false;
        }
        return true;
    }

    protected function whetherThisIpAccepted()
    {
        $ipArr = explode(',', env("APP_IP_chatbox", ""));
        \Request::setTrustedProxies([\Request::ip()]);

        if ($ipArr && !in_array(\Request::ip(), $ipArr)) {
            return false;
        }
        return true;
    }
}

参考

https://www.messiahworks.com/archives/14930
http://pdo99.hatenablog.com/entry/2017/06/27/175316

その他の手法

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0