How to get the client IP using a Symfony 4 application hosted on Azure Web App

Cid :

I want to log every login attempts on a Web App (Symfony 4.1) hosted on Azure.

Based on this question, to get the client IP, I'm using :

// $requestStack being Symfony\Component\HttpFoundation\RequestStack
$ip = $this->requestStack->getMasterRequest()->getClientIp();

However, the logs tell :

[2020-03-10 10:55:56] login_attempt.INFO: User 'username' successfully logged in from ip '172.16.1.1' [] []

As you can notice, this is a private IP. I tried to log in from differents connections, but I'm always getting that IP, 172.16.1.1. Where does this IP come from and how to get the real public IP of the client ?

Cid :

That private IP can be a load balancer or a reverse proxy.

From documentation :

When you deploy your application, you may be behind a load balancer (e.g. an AWS Elastic Load Balancing) or a reverse proxy (e.g. Varnish for caching).

For the most part, this doesn't cause any problems with Symfony. But, when a request passes through a proxy, certain request information is sent using either the standard Forwarded header or X-Forwarded-* headers. For example, instead of reading the REMOTE_ADDR header (which will now be the IP address of your reverse proxy), the user's true IP will be stored in a standard Forwarded: for="..." header or a X-Forwarded-For header.

If you don't configure Symfony to look for these headers, you'll get incorrect information about the client's IP address, whether or not the client is connecting via HTTPS, the client's port and the hostname being requested.

To fix that, one can add that IP in the trusted proxies of the application.

In Symfony 4, this can be done this way :

// index.php

// creates the $_SERVER['TRUSTED_PROXIES'] entry if it doesn't exist/is empty with the IP of the proxy to trust as value
// or append ',the ip' to the existing entry
$_SERVER['TRUSTED_PROXIES'] = (empty($_SERVER['TRUSTED_PROXIES']) ? '' : ($_SERVER['TRUSTED_PROXIES'] . ',')) . '172.16.1.1';

// This is already in index.php, just let it doing its job
if ($trustedProxies = $_SERVER['TRUSTED_PROXIES'] ?? false) {
    Request::setTrustedProxies(explode(',', $trustedProxies), Request::HEADER_X_FORWARDED_ALL ^ Request::HEADER_X_FORWARDED_HOST);
}

And now, in the logs :

[2020-03-10 13:09:06] login_attempt.INFO: User 'username' successfully logged in from ip 'the public ip address' [] []

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=342580&siteId=1