如何限制单个IP地址访问Flask? [英] How to limit access to Flask for a single IP address?

查看:1111
本文介绍了如何限制单个IP地址访问Flask?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Python Flask框架开发一个网站,现在我做了一些改进,推动了我的改变到远程开发服务器.我将此远程开发服务器设置为使用app.run(host='0.0.0.0')公开服务网站.

I'm developing a website using the Python Flask framework and I now do some devving, pushing my changes to a remote dev server. I set this remote dev server up to serve the website publically using app.run(host='0.0.0.0').

这很好,但是我只是不希望其他人查看我的网站.因此,我想以某种方式将我的IP列入白名单,以便开发服务器仅将网站服务到我自己的IP地址,而没有响应,404或其他无用的响应给其他IP地址.我当然可以将服务器设置为使用apache或nginx实际为网站提供服务,但是我喜欢在代码更改时自动重新加载网站以开发我的网站

This works fine, but I just don't want other people to view my website yet. For this reason I somehow want to whitelist my ip so that the dev server only serves the website to my own ip address, giving no response, 404's or some other non-useful response to other ip addresses. I can of course set up the server to use apache or nginx to actually serve the website, but I like the automatic reloading of the website on code changes for devving my website

因此,有人知道使用内置的Flask开发服务器来执行此操作的方法吗?欢迎所有提示!

So does anybody know of a way to do this using the built in Flask dev server? All tips are welcome!

推荐答案

使用 just Flask的功能,您可以使用

Using just the features of Flask, you could use a before_request() hook testing the request.remote_addr attribute:

from flask import abort, request

@app.before_request
def limit_remote_addr():
    if request.remote_addr != '10.20.30.40':
        abort(403)  # Forbidden

但是在服务器上使用防火墙规则可能是更安全,更可靠的选择.

but using a firewall rule on the server is probably the safer and more robust option.

请注意,如果浏览器和服务器之间存在反向代理,则可以屏蔽Remote_Addr.请注意如何限制这一点,不要将自己锁在门外.如果代理位于服务器本身附近(例如负载平衡器或前端缓存),则可以检查

Note that the Remote_Addr can be masked if there is a reverse proxy in between the browser and your server; be careful how you limit this and don't lock yourself out. If the proxy lives close to the server itself (like a load balancer or front-end cache), you can inspect the request.access_route list to access the actual IP address. Do this only if remote_addr itself is a trusted IP address too:

trusted_proxies = ('42.42.42.42', '82.42.82.42', '127.0.0.1')

def limit_remote_addr():
    remote = request.remote_addr
    route = list(request.access_route)
    while remote in trusted_proxies:
        remote = route.pop()

    if remote != '10.20.30.40':
        abort(403)  # Forbidden

这篇关于如何限制单个IP地址访问Flask?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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