10
19

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

LaravelでIPによるアクセス制限をする

Posted at

はじめに

管理画面であったり開発環境であったり、アクセス拠点元のIPで制限を行いたい場面に出くわすことがあるかと思います。
.htaccessファイルで制限したり、AWSのALB(Application Load Balancer)で大本から制限する事もできますが、
手軽に実装しつつも画面によってIP制限を切り分けたい~だとか、許可されないIPの場合でも任意のメッセージを表示してあげたい~…
といった場合は、ミドルウェアで実装してrouteに対して割り当ててやるのが一番簡単かなと思います。

Laravelのバージョンは5.7にて確認しています。

Middleware

本番環境とステージング環境の場合だけ、特定のIPアドレスでアクセスを制限してみます。

下記では予め許可されたIPの一覧を配列に用意しておき、アクセス元のIPが配列に含まれているかどうかで制限しています。
どのIPがどの拠点か分かるようにIPアドレスと共に拠点の名前などを残しておくと管理する上で便利でしょう。

今回は許可されていないIPアドレスの場合は403エラーへ飛ばしています。

app\Http\Middleware\CheckIPAddress.php
<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\App;

class CheckIPAddress
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @param  string|null  $guard
     * @return mixed
     */
    public function handle($request, Closure $next, $guard = null)
    {
        if (App::environment(['staging', 'production'])) {
            $ip = [
                ['id' => 1, 'ip' => '192.168.0.1', 'name' => 'office-1'],
                ['id' => 2, 'ip' => '192.168.0.2', 'name' => 'office-2'],
                ['id' => 3, 'ip' => '192.168.0.3', 'name' => '自宅'],
            ];

            // check your ip
            $detect = collect($ip)->contains('ip', $request->ip());

            if (!$detect) {
                abort(403);
            }
        }

        return $next($request);
    }
}

次に、上記のミドルウェアを登録します。

routeに対してミドルウェアを割り当てる場合はルートミドルウェアに登録し…

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 = [
        'checkIP' => \App\Http\Middleware\CheckIPAddress::class,
    ];

routeでミドルウェアを割り当ててやります。

routes\web.php
Route::group(['middleware' => 'checkIP'], function () {
    Route::get('mypage/{slug}', ['uses' => 'MypageController@index'])->name('mypage.show');
});

そもそもアプリケーションの全HTTPリクエスト対して制限したいんだ、という場合はグローバルミドルウェアに登録すればOKです。

app\Http\Kernel.php
<?php

namespace App\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel
{
    /**
     * The application's global HTTP middleware stack.
     *
     * These middleware are run during every request to your application.
     *
     * @var array
     */
    protected $middleware = [
        \App\Http\Middleware\CheckIPAddress::class,
    ];

おわりに

調べれば同じような情報はいくらでも出てくるんですが、自分用の備忘録として…

10
19
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
10
19

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?