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.
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