【问题标题】:How to get the client IP using a Symfony 4 application hosted on Azure Web App如何使用托管在 Azure Web App 上的 Symfony 4 应用程序获取客户端 IP
【发布时间】:2020-03-10 12:46:11
【问题描述】:

我想记录在 Azure 上托管的 Web 应用 (Symfony 4.1) 上的每次登录尝试。

基于this question,获取客户端IP,我正在使用:

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

但是,日志告诉我们:

[2020-03-10 10:55:56] login_attempt.INFO: 用户 'username' 从 ip '172.16.1.1' 成功登录 [] []

如您所见,这是一个私有 IP。我试图从不同的连接登录,但我总是得到那个 IP,172.16.1.1。这个IP是从哪里来的,如何获取客户端的真实公网IP?

【问题讨论】:

    标签: php symfony azure-web-app-service symfony4


    【解决方案1】:

    该私有 IP 可以是负载均衡器或反向代理。

    来自documentation

    当您部署应用程序时,您可能会使用负载均衡器(例如 AWS Elastic Load Balancing)或反向代理(例如用于缓存的 Varnish)。

    在大多数情况下,这不会对 Symfony 造成任何问题。但是,当请求通过代理时,某些请求信息会使用标准的Forwarded 标头或X-Forwarded-* 标头发送。 例如,用户的真实 IP 将存储在标准 Forwarded: for="..." 标头或 X-Forwarded-For 标头中,而不是读取 REMOTE_ADDR 标头(现在将是您的反向代理的 IP 地址)强>。

    如果您没有配置 Symfony 来查找这些标头,您将获得有关客户端 IP 地址、客户端是否通过 HTTPS 连接、客户端端口和请求的主机名的错误信息。

    要解决这个问题,可以将该 IP 添加到应用程序的受信任代理中。

    在 Symfony 4 中,可以这样完成:

    // 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);
    }
    

    现在,在日志中:

    [2020-03-10 13:09:06] login_attempt.INFO: 用户 'username' 从 ip '公共 ip 地址' 成功登录 [] []

    【讨论】:

      猜你喜欢
      • 2021-01-19
      • 2014-02-21
      • 1970-01-01
      • 2020-09-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-01
      • 2015-08-08
      相关资源
      最近更新 更多