Last modified: Apr 27, 2025 By Alexander Williams
Python Flask: Restrict Access by IP Address
Securing a Flask app is crucial. One way is by restricting access based on IP addresses. This ensures only trusted users can access your app.
This guide shows how to implement IP-based access control in Flask. You'll learn to allow or block specific IPs easily.
Table Of Contents
Why Restrict Access by IP Address?
IP restriction adds a security layer. It prevents unauthorized access to your app. This is useful for admin panels or internal tools.
Common use cases include limiting access to office networks or specific servers. It's a simple yet effective security measure.
Getting the Client IP Address in Flask
First, you need to get the client's IP address. Flask provides this in the request object.
from flask import Flask, request
app = Flask(__name__)
@app.route('/')
def home():
client_ip = request.remote_addr
return f"Your IP is: {client_ip}"
The request.remote_addr
gives the client's IP. For apps behind proxies, use request.headers.get('X-Forwarded-For')
.
If you need to extract IPs from text, see our guide on extracting IP addresses from text in Python.
Implementing IP Whitelisting
Whitelisting allows only specific IPs to access your app. Others get blocked. Here's how to implement it.
ALLOWED_IPS = ['192.168.1.1', '10.0.0.1']
@app.before_request
def restrict_ip():
client_ip = request.remote_addr
if client_ip not in ALLOWED_IPS:
return "Access denied", 403
The before_request
decorator runs before each request. It checks if the IP is in the allowed list.
For more IP handling, learn about detecting private vs public IPs in Python.
Implementing IP Blacklisting
Blacklisting blocks specific IPs while allowing others. Here's the implementation.
BLOCKED_IPS = ['123.45.67.89', '98.76.54.32']
@app.before_request
def block_ip():
client_ip = request.remote_addr
if client_ip in BLOCKED_IPS:
return "Your IP is blocked", 403
This code checks if the IP is in the blocked list. If yes, it returns a 403 error.
Using IP Ranges and Subnets
Sometimes you need to allow/block IP ranges. The ipaddress
module helps with this.
import ipaddress
ALLOWED_NETWORK = ipaddress.IPv4Network('192.168.1.0/24')
@app.before_request
def check_ip_range():
client_ip = ipaddress.IPv4Address(request.remote_addr)
if client_ip not in ALLOWED_NETWORK:
return "IP not in allowed network", 403
For subnet operations, see our guide on subnetting IP addresses in Python.
Handling Proxy Servers
If your app is behind a proxy, you need to check the X-Forwarded-For header.
@app.before_request
def check_proxied_ip():
if request.headers.getlist("X-Forwarded-For"):
client_ip = request.headers.getlist("X-Forwarded-For")[0]
else:
client_ip = request.remote_addr
if client_ip not in ALLOWED_IPS:
return "Access denied", 403
Complete Example
Here's a complete Flask app with IP restriction.
from flask import Flask, request
import ipaddress
app = Flask(__name__)
ALLOWED_IPS = ['192.168.1.1', '10.0.0.1']
ALLOWED_NETWORK = ipaddress.IPv4Network('192.168.1.0/24')
@app.before_request
def restrict_access():
# Get client IP
if request.headers.getlist("X-Forwarded-For"):
client_ip = request.headers.getlist("X-Forwarded-For")[0]
else:
client_ip = request.remote_addr
# Check whitelist
if client_ip not in ALLOWED_IPS:
try:
ip_obj = ipaddress.IPv4Address(client_ip)
if ip_obj not in ALLOWED_NETWORK:
return "Access denied", 403
except:
return "Invalid IP", 400
@app.route('/')
def home():
return "Welcome! Access granted."
if __name__ == '__main__':
app.run()
Testing Your Implementation
Test your IP restrictions using different clients. You can also use tools like curl.
curl http://your-flask-app.com
For testing with specific IPs, see our guide on setting custom source IPs in Python Requests.
Conclusion
IP-based access control is a simple security measure for Flask apps. It helps protect sensitive endpoints from unauthorized access.
Remember to handle proxy headers correctly. Also consider combining this with other security measures for better protection.
For more advanced networking, explore our guide on handling multiple IP connections with AsyncIO.