我有一个连接了多个运行AWS Flask服务器的EC2实例的AWS ELB。我不确定AWS ELB是否会将完整请求传递给EC2。我知道我们可以在ELB层面实现限制,但我只想对一个端点进行限制,并验证调用Flask端点的服务器的主机名。这是否可能?
您可以尝试以下方法:
import socket
from flask import request
@app.route("/your_route", methods=["GET"])
def your_route():
hostname, aliaslist, ipaddrlist = socket.gethostbyaddr(request.remote_addr)
socket.gethostbyaddr()
的更多信息,请查看:socket.gethostbyaddr()。我建议您在这种情况下使用装饰器模式,即添加一个名为IP_LIST的新配置选项,其中包含用逗号分隔的地址集。
IP_LIST = "127.0.0.1,127.0.0.2,..."
接下来添加一个新的装饰器函数,并使用该装饰器装饰任何端点。
def ip_verified(fn):
"""
A custom decorator that checks if a client IP is in the list, otherwise block access.
"""
@wraps(fn)
def decorated_view(*args, **kwargs):
ip_list_str = current_app.config['IP_LIST']
ip_list = ip_list_str.split(",") if ip_list_str else []
if request.headers.getlist("X-Forwarded-For"):
remote_ip = request.headers.getlist("X-Forwarded-For")[0]
else:
remote_ip = request.remote_addr
if remote_ip not in ip_list:
return "Not sufficient privileges", 403
return fn(*args, **kwargs)
return decorated_view
@app.route("/your_route", methods=["GET"])
@ip_verified
def your_route():
...