【问题标题】:Properly forwarding visitor's IP address from flask_restful to nginx将访问者的 IP 地址从 flask_restful 正确转发到 nginx
【发布时间】:2022-04-04 17:20:36
【问题描述】:

我正在运行 flask_restful API 服务,该服务通过 nginx 代理转发流量。当 IP 地址通过代理通过一些变量转发时,flask_restful 似乎无法看到这些变量,如其输出所示,它指向 127.0.0.1:

127.0.0.1 - - [25/Oct/2017 21:55:37] "HEAD sne/event/SN2014J/photometry HTTP/1.0" 200 -

虽然我知道我可以通过request 对象检索IP 地址(nginx 转发X-Forwarded-ForX-Real-IP),但我不知道如何使flask_restful 的上述输出显示/使用此IP地址,如果你想说限制来自给定 IP 地址的 API 调用次数,这很重要flask_limiter。有什么办法可以做到这一点?

【问题讨论】:

标签: nginx flask flask-restful nginx-reverse-proxy


【解决方案1】:

您可以使用(对于较旧版本的 werkzeug)

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

对于较新版本的 werkzeug (1.0.0+)

from werkzeug.middleware.proxy_fix import ProxyFix
app.wsgi_app = ProxyFix(app.wsgi_app)

这将使用X-Forwarded-For 修复IP。如果您需要增强版本,请使用

class SaferProxyFix(object):
    """This middleware can be applied to add HTTP proxy support to an
    application that was not designed with HTTP proxies in mind.  It
    sets `REMOTE_ADDR`, `HTTP_HOST` from `X-Forwarded` headers.
    
    If you have more than one proxy server in front of your app, set
    num_proxy_servers accordingly
    Do not use this middleware in non-proxy setups for security reasons.
    
    get_remote_addr will raise an exception if it sees a request that 
    does not seem to have enough proxy servers behind it so long as
    detect_misconfiguration is True.
    The original values of `REMOTE_ADDR` and `HTTP_HOST` are stored in
    the WSGI environment as `werkzeug.proxy_fix.orig_remote_addr` and
    `werkzeug.proxy_fix.orig_http_host`.
    :param app: the WSGI application
    """

    def __init__(self, app, num_proxy_servers=1, detect_misconfiguration=False):
        self.app = app
        self.num_proxy_servers = num_proxy_servers
        self.detect_misconfiguration = detect_misconfiguration

    def get_remote_addr(self, forwarded_for):
        """Selects the new remote addr from the given list of ips in
        X-Forwarded-For.  By default the last one is picked. Specify
        num_proxy_servers=2 to pick the second to last one, and so on.
        """
        if self.detect_misconfiguration and not forwarded_for:
            raise Exception("SaferProxyFix did not detect a proxy server. Do not use this fixer if you are not behind a proxy.")
        if self.detect_misconfiguration and len(forwarded_for) < self.num_proxy_servers:
            raise Exception("SaferProxyFix did not detect enough proxy servers. Check your num_proxy_servers setting.")
            
        if forwarded_for and len(forwarded_for) >= self.num_proxy_servers:
            return forwarded_for[-1 * self.num_proxy_servers]

    def __call__(self, environ, start_response):
        getter = environ.get
        forwarded_proto = getter('HTTP_X_FORWARDED_PROTO', '')
        forwarded_for = getter('HTTP_X_FORWARDED_FOR', '').split(',')
        forwarded_host = getter('HTTP_X_FORWARDED_HOST', '')
        environ.update({
            'werkzeug.proxy_fix.orig_wsgi_url_scheme':  getter('wsgi.url_scheme'),
            'werkzeug.proxy_fix.orig_remote_addr':      getter('REMOTE_ADDR'),
            'werkzeug.proxy_fix.orig_http_host':        getter('HTTP_HOST')
        })
        forwarded_for = [x for x in [x.strip() for x in forwarded_for] if x]
        remote_addr = self.get_remote_addr(forwarded_for)
        if remote_addr is not None:
            environ['REMOTE_ADDR'] = remote_addr
        if forwarded_host:
            environ['HTTP_HOST'] = forwarded_host
        if forwarded_proto:
            environ['wsgi.url_scheme'] = forwarded_proto
        return self.app(environ, start_response)

from saferproxyfix import SaferProxyFix
app.wsgi_app = SaferProxyFix(app.wsgi_app)

PS:代码取自http://esd.io/blog/flask-apps-heroku-real-ip-spoofing.html

【讨论】:

    猜你喜欢
    • 2017-03-19
    • 1970-01-01
    • 1970-01-01
    • 2023-04-11
    • 2023-03-31
    • 2015-03-01
    • 1970-01-01
    • 2021-07-31
    • 2013-11-21
    相关资源
    最近更新 更多