3
0

More than 3 years have passed since last update.

AWS ALB環境下のlaravel-adminにてRequest::ip()が正しく取得出来ずにハマった

Last updated at Posted at 2021-03-17

PHP7.4系 Laravel5.8 laravel-admin1.8.11の環境において、で正しくクライアントIPが取得出来ず、IP制限やSSL関連挙動が変わってしまった。laravel-admin1.7系では問題無かった為、試行錯誤のメモを残す。

Request::ip();

TrustProxiesが正しく動かない!?

本来、AWS Elastic Load Balancingを使用している場合、
$headersの値はRequest::HEADER_X_FORWARDED_AWS_ELBに設定する必要があると公式ドキュメントに記載あり。
https://readouble.com/laravel/5.8/ja/requests.html

app/Http/Middleware/TrustProxies.php

<?php

namespace App\Http\Middleware;

use Illuminate\Http\Request;
use Fideloper\Proxy\TrustProxies as Middleware;

class TrustProxies extends Middleware
{
    /**
     * このアプリケーションで信用するプロキシ
     *
     * @var array
     */
    protected $proxies = '*';

    /**
     * プロキシを検出するために使用するヘッダ
     *
     * @var string
     */
    protected $headers = Request::HEADER_X_FORWARDED_AWS_ELB;
}

TrustProxies周りをあれこれ(HEADER_X_FORWARDED_AWS_ELBなど)見てみるが解消しない。

原因

コード辿ってdebug_backtraceなどしてみると、どうやらLogOperation関連の挙動がおかしいことに気がつく。

https://github.com/z-song/laravel-admin/compare/v1.8.4...master
laravel-admin 1.8.4リリース時にプッシュされたコードが原因と判明。

(この箇所)
https://github.com/z-song/laravel-admin/commit/95d2cacd46a1429780cc58272d14f8709db3be98

解消方法(暫定)

vendor/encore/laravel-admin/src/Middleware/LogOperation.php
    public function handle(Request $request, \Closure $next)
    {
        if ($this->shouldLogOperation($request)) {
            //$setProxy = $request->setTrustedProxies(request()->getClientIps(), \Illuminate\Http\Request::HEADER_X_FORWARDED_FOR); 
            // ↑ここをコメントアウト
            $log = [
                'user_id' => Admin::user()->id,
                'path'    => substr($request->path(), 0, 255),
                'method'  => $request->method(),
                'ip'      => $request->getClientIp(),
                'input'   => json_encode($request->input()),

25行目をコメントアウトする事で解消。
setTrustedProxies が TrustProxies側と重複していると思われる。

取り急ぎGitHubにコメント残しつつ、当該箇所をオーバライドして暫定回避で対応する事とする。

環境

PHP: 7.4.14
Laravel: 5.8.38
laravel-admin: 1.8.11

3
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
3
0