在 Heroku 上获取客户端的真实 IP 地址 [英] Get client's real IP address on Heroku

查看:21
本文介绍了在 Heroku 上获取客户端的真实 IP 地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Heroku Cedar 上,我想获取客户端的 IP.第一次尝试:

On Heroku Cedar, I wanted to get the client's IP. First attempt:

ENV['REMOTE_ADDR']

这当然行不通,因为所有请求都是通过代理传递的.所以替代方案是使用:

This does not work, of course, because all requests are passed through proxies. So the alternative was to use:

ENV['HTTP_X_FORWARDED_FOR']

但这不太安全,是吗?

如果它只包含一个值,我就接受这个.如果它包含多个值(逗号分隔),我可以取第一个.

If it contains only one value, I take this. If it contains more than one value (comma-separated), I could take the first one.

但是如果有人操纵这个值怎么办?我不能像使用 ENV['REMOTE_ADDR'] 那样信任 ENV['HTTP_X_FORWARDED_FOR'].而且也没有我可以使用的受信任代理列表.

But what if someone manipulates this value? I cannot trust ENV['HTTP_X_FORWARDED_FOR'] as I could with ENV['REMOTE_ADDR']. And there is no list of trusted proxies that I could use, either.

但是必须有某种方法来可靠地获取客户端的 IP 地址,始终如此.你知道吗?

But there must be some way to reliably get the client's IP address, always. Do you know one?

他们的文档中,Heroku 描述了 X-Forwarded-For 是连接到 Heroku 路由器的客户端的原始 IP 地址".

In their docs, Heroku describes that X-Forwarded-For is "the originating IP address of the client connecting to the Heroku router".

这听起来好像 Heroku 可以用原始远程 IP 覆盖 X-Forwarded-For.这样可以防止欺骗,对吧?有人可以验证吗?

This sounds as if Heroku could be overwriting the X-Forwarded-For with the originating remote IP. This would prevent spoofing, right? Can someone verify this?

推荐答案

来自当时 Heroku 的安全总监 Jacob:

From Jacob, Heroku's Director of Security at the time:

路由器不会覆盖X-Forwarded-For,但它确实保证真正的来源始终是列表中的最后项.

The router doesn't overwrite X-Forwarded-For, but it does guarantee that the real origin will always be the last item in the list.

这意味着,如果您以正常方式访问 Heroku 应用程序,您只会在 X-Forwarded-For 标头中看到您的 IP 地址:

This means that, if you access a Heroku app in the normal way, you will just see your IP address in the X-Forwarded-For header:

$ curl http://httpbin.org/ip
{
  "origin": "123.124.125.126",
}

如果您试图欺骗 IP,您所谓的来源 会得到反映,但 - 关键是 - 您的真实 IP 也是如此.显然,这就是我们所需要的,所以有一个清晰且安全的解决方案来在 Heroku 上获取客户端的 IP 地址:

If you try to spoof the IP, your alleged origin is reflected, but - critically - so is your real IP. Obviously, this is all we need, so there's a clear and secure solution for getting the client's IP address on Heroku:

$ curl -H"X-Forwarded-For: 8.8.8.8" http://httpbin.org/ip
{
  "origin": "8.8.8.8, 123.124.125.126"
}

这与维基百科上的描述相反,顺便说一句.

PHP 实现:

function getIpAddress() {
    if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $ipAddresses = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
        return trim(end($ipAddresses));
    }
    else {
        return $_SERVER['REMOTE_ADDR'];
    }
}

这篇关于在 Heroku 上获取客户端的真实 IP 地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆