Flask request.remote_addr在webfaction上出错,没有显示真正的用户IP

2024-10-02 18:27:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我刚刚在Webfaction上部署了一个Flask应用程序,我注意到request.remote_addr总是127.0.0.1。这当然没什么用。

我如何才能得到真正的IP地址的用户在烧瓶在网络势力?

谢谢!


Tags: 用户网络应用程序flask烧瓶remoterequest部署
3条回答

Werkzeug中间件

Flask的文档非常具体about recommended reverse proxy server setup

If you deploy your application using one of these [WSGI] servers behind an HTTP [reverse] proxy you will need to rewrite a few headers in order for the application to work [properly]. The two problematic values in the WSGI environment usually are REMOTE_ADDR and HTTP_HOST... Werkzeug ships a fixer that will solve some common setups, but you might want to write your own WSGI middleware for specific setups.

关于安全考虑:

Please keep in mind that it is a security issue to use such a middleware in a non-proxy setup because it will blindly trust the incoming headers which might be forged by malicious clients.

建议的代码(安装中间件)将使request.remote_addr返回客户端IP地址为:

from werkzeug.contrib.fixers import ProxyFix
app.wsgi_app = ProxyFix(app.wsgi_app, num_proxies=1)

注意num_proxies,默认为1。这是应用程序前面的代理服务器数。

实际代码如下(编写时的最后一个werkzeug==0.14.1):

def get_remote_addr(self, forwarded_for):
    if len(forwarded_for) >= self.num_proxies:
        return forwarded_for[-self.num_proxies]

网络势力

Webfaction关于Accessing ^{}的文档说:

...the IP address is available as the first IP address in the comma separated list in the HTTP_X_FORWARDED_FOR header.

他们不会说当客户机请求已经包含X-Forwarded-For头时他们会做什么,但是根据常识,我假设他们会替换它。因此,对于Webfaction,应该将num_proxies设置为0

Nginx公司

Nginx更明确地说是^{}

the “X-Forwarded-For” client request header field with the $remote_addr variable appended to it, separated by a comma. If the “X-Forwarded-For” field is not present in the client request header, the $proxy_add_x_forwarded_for variable is equal to the $remote_addr variable.

对于应用程序前面的Nginx,num_proxies应该保留默认值1

改写伊格纳斯的回答:

headers_list = request.headers.getlist("X-Forwarded-For")
user_ip = headers_list[0] if headers_list else request.remote_addr

记住阅读Eli's post关于欺骗的注意事项。

如果烧瓶前面有一个代理,那么这样的东西将得到烧瓶中的真正IP:

if request.headers.getlist("X-Forwarded-For"):
   ip = request.headers.getlist("X-Forwarded-For")[0]
else:
   ip = request.remote_addr

更新:伊莱在评论中提到了非常好的观点。如果你只是简单地使用它,可能会有一些安全问题。阅读Eli's post获取更多详细信息。

相关问题 更多 >