如何正确使用HTTP_X_FORWARDED_FOR? [英] How to use HTTP_X_FORWARDED_FOR properly?
问题描述
好吧,我的身份验证问题很小。我的Web服务允许通过HTTP使用用户名和密码连接到我的API,但此连接也可以限制为特定的IP地址。
Alright, I have an small authentication issue. My web service allows to connect to my API over HTTP with a username and password, but this connection can also be restricted to a specific IP address.
这意味着 $ _ SERVER ['REMOTE_ADDR']
可能不正确。我已经知道任何IP信息都无法真正依赖 - 我只有在尝试添加另一层安全性时才有限制。
This means that the $_SERVER['REMOTE_ADDR']
can be incorrect. I already know that any IP information can never truly be relied upon - I have the restriction only in an attempt to add another layer of security.
如果这是一般概述请求到我的网络服务器:
If this is the general overview of a request to my web server:
clientSERVER => clientPROXY => myPROXY => mySERVER
然后这意味着mySERVER显示myPROXY的 REMOTE_ADDR
而不是客户端并将客户端的实际IP发送为 HTTP_X_FORWARDED_FOR
。
Then this means that mySERVER shows REMOTE_ADDR
of myPROXY instead of that of the client and sends the actual IP of the client as HTTP_X_FORWARDED_FOR
.
为了解决这个问题,我的Web服务有一个列表'可信代理'IP地址以及 REMOTE_ADDR
来自其中一个可信IP地址,然后它告诉我的Web服务实际IP地址是<$ c的值$ c> HTTP_X_FORWARDED_FOR 。
To overcome this, my web service has a list of 'trusted proxy' IP addresses and if REMOTE_ADDR
is from one of those trusted IP addresses, then it tells my web service that the actual IP address is the value of HTTP_X_FORWARDED_FOR
.
现在问题在于clientPROXY。这意味着(通常)mySERVER获取具有多个IP地址的 HTTP_X_FORWARDED_FOR
值。根据 HTTP_X_FORWARDED_FOR
文档,该值是以逗号分隔的IP地址列表,其中第一个IP是实际真实客户端的IP,每个其他IP地址是代理的IP地址。
Now the problem is with clientPROXY. This means that (quite often) mySERVER gets HTTP_X_FORWARDED_FOR
value that has multiple IP addresses. According to HTTP_X_FORWARDED_FOR
documentation, the value is a comma-separated list of IP addresses where the first IP is that of the actual true client and every other IP address is that of a proxy.
因此,如果 HTTP_X_FORWARDED_FOR
有多个值且我的服务受IP限制,我是否必须检查'对我允许的IP列表的最后一个'code> HTTP_X_FORWARDED_FOR 的值,只是忽略实际的客户端IP?
So, if HTTP_X_FORWARDED_FOR
has multiple values and my service is IP restricted, do I have to check the 'last' value of HTTP_X_FORWARDED_FOR
against my allowed IP list and just ignore the actual client IP?
我假设在一个系统,我必须设置允许的IP地址列表,白名单IP地址应该是代理的IP地址而不是代理后面的IP(因为那可能是一些本地主机IP并经常更改)。
I assume that in a system, where I have to set the list of allowed IP addresses, the whitelisted IP address should be that of a proxy and not an IP that is behind the proxy (since that could be some localhost IP and change frequently).
什么是 HTTP_CLIENT_IP
?
推荐答案
您可以使用此功能获取正确的客户端IP:
You can use this function to get proper client IP:
public function getClientIP(){
if (array_key_exists('HTTP_X_FORWARDED_FOR', $_SERVER)){
return $_SERVER["HTTP_X_FORWARDED_FOR"];
}else if (array_key_exists('REMOTE_ADDR', $_SERVER)) {
return $_SERVER["REMOTE_ADDR"];
}else if (array_key_exists('HTTP_CLIENT_IP', $_SERVER)) {
return $_SERVER["HTTP_CLIENT_IP"];
}
return '';
}
这篇关于如何正确使用HTTP_X_FORWARDED_FOR?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!