3
6

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 5 years have passed since last update.

CakePHP3.2.4 -> 3.2.5 で変更された$this->request->clientIp()について

Posted at

CakePHP3.2.5で、Cake\Network\Request::clientIp()が変更され、HTTP_CLIENT_IPを見るのはRequest::trustProxytrueの時のみになりました。(HTTP_CLIENT_IPは偽装されるおそれがあるため。)

なので、ロードバランサーやプロキシを介している場合は、

$this->request->trustProxy = true;
$clientIp = $this->request->clientIp();

とすれば、今までのようにHTTP_X_FORWARDED_FORHTTP_CLIENT_IPを見ますが、trustProxyfalseの場合(デフォルト)なら、REMOTE_ADDRだけを見ます。(以前はHTTP_CLIENT_IPHTTP_CLIENTADDRESSも見ていた。)

というわけで、今まで$this->request->clientIp()を使っていたものが、CakePHP3.2.5へのバージョンアップでそのまま動くかどうかは、少し確認が必要だと思います。(元々REMOTE_ADDRの値が使われていた場合は問題ないはず。)

ユニットテストについて

clientIp()を使用してアクセス制御をしているような部分をテストする場合、私は、

tests/TestCase/Controller/ArticlesControllerTest.php
public function testIpOk()
{
    $allowedIp = '192.168.1.1';
    $this->configRequest([
        'headers' => ['CLIENT_IP' => $allowedIp]
    ]);
    $this->get('/articles');
    $this->assertResponseOk();
}

という感じで、configRequest()headersCLIENT_IPを指定(HTTP_CLIENT_IPがセットされることになる)していたのですが、これだと今回の更新でclientIp()から値が返ってこなくなります。
headersに指定すると勝手にHTTP_が頭に付くし、REMOTE_ADDRを指定するにはどうしたら、、、と思ってたら、environmentでセットできました。 :clap:

tests/TestCase/Controller/ArticlesControllerTest.php
public function testIpOk()
{
    $allowedIp = '192.168.1.1';
    $this->configRequest([
        'environment' => ['REMOTE_ADDR' => $allowedIp]
    ]);
    $this->get('/articles');
    $this->assertResponseOk();
}
3
6
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
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?