Flask Allowed Hosts
Flask Allowed Hosts is a Flask extension that provides validation for both hostnames and IP addresses for API endpoints. It enforces access restrictions, allowing only requests from specified hosts or IPs, an additional layer of security to your Flask application.
While CORS is effective in browsers for preventing unauthorized origins, it does not protect against non-browser requests. This package addresses that limitation by permitting access only to the hostnames and IPs listed in the allowed_hosts, effectively limiting access to your API from unknown sources.
Installation
Install the package using pip:
pip install flask-allowed-hosts
Getting Started
To limit access to your routes using flask-allowed-hosts:
Basic usage of the limit decorator:
Here’s how to set up host validation for a basic endpoint:
from flask import Flask, request, jsonify
from flask_allowed_hosts import AllowedHosts
ALLOWED_HOSTS = ["123.123.123.123", "321.321.321.321"]
# Returns a json response if the request IP is not in the allowed hosts
def on_denied():
error = {"error": "Oops! looks like you are not allowed to access this page!"}
return jsonify(error), 403
app = Flask(__name__)
allowed_hosts = AllowedHosts(app, allowed_hosts=ALLOWED_HOSTS, on_denied=on_denied)
@app.route("/api/greet", methods=["GET"])
@allowed_hosts.limit()
def greet_endpoint():
name = request.args.get("name", "Friend")
greeting = {"greeting": f"Hello There {name}!"}
return jsonify(greeting), 200
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000, debug=True)
Overriding the allowed_hosts or on_denied parameters for a specific route:
You can override the allowed_hosts or on_denied parameters for specific routes like this:
from flask import Flask, request, jsonify
from flask_allowed_hosts import AllowedHosts
ALLOWED_HOSTS = ["123.123.123.123", "321.321.321.321"]
# Returns a json response if the request IP is not in the allowed hosts
def on_denied():
error = {"error": "Oops! looks like you are not allowed to access this page!"}
return jsonify(error), 403
app = Flask(__name__)
allowed_hosts = AllowedHosts(app, allowed_hosts=ALLOWED_HOSTS, on_denied=on_denied)
@app.route("/api/greet", methods=["GET"])
@allowed_hosts.limit(allowed_hosts=["127.0.0.1", "localhost"])
def greet_endpoint():
name = request.args.get("name", "Friend")
greeting = {"greeting": f"Hello There {name}!"}
return jsonify(greeting), 200
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000, debug=True)
Using the legacy limit_hosts decorator:
If you prefer to use the legacy limit_hosts decorator, you can do so as follows:
from flask import Flask, request, jsonify
from flask_allowed_hosts import limit_hosts
ALLOWED_HOSTS = ["123.123.123.123", "321.321.321.321"]
# Returns a json response if the request IP is not in the allowed hosts
def on_denied():
error = {"error": "Oops! looks like you are not allowed to access this page!"}
return jsonify(error), 403
app = Flask(__name__)
@app.route("/api/greet", methods=["GET"])
@limit_hosts(allowed_hosts=ALLOWED_HOSTS, on_denied=on_denied)
def greet_endpoint():
name = request.args.get("name", "Friend")
greeting = {"greeting": f"Hello There {name}!"}
return jsonify(greeting), 200
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000, debug=True)
For more examples you can check examples.
Parameters
AllowedHosts class
-
app: Flask: The Flask app object. -
allowed_hosts: [List[str], str]: Modify this list to include the allowed hosts. The default value is an empty list[], which means requests from all hosts are allowed. -
on_denied: Callable: Modify this function to customize the behavior when a request is denied. The default isNone, which means a 403 Forbidden error is returned.
@AllowedHosts.limit decorator
-
allowed_hosts: [List[str], str]: Modify this list to override the allowed hosts list set inAllowedHosts. The default value is what you set in theAllowedHostsinstance. -
on_denied: Callable: Modify this function to customize the behavior when a request is denied. The default value is what you set in theAllowedHostsinstance.
@limit_hosts decorator (legacy)
-
allowed_hosts: [List[str], str]: Modify this list to include the allowed hosts. The default value isNone, which means requests from all hosts are allowed. -
on_denied: Callable: Modify this function to customize the behavior when a request is denied. The default isNone, which means a 403 Forbidden error is returned.
Contributing
Contributions are welcome! If you have any suggestions, bug reports, or feature requests, please open an issue or submit a pull request.
License
This project is licensed under the [MIT] License - see the LICENSE.md file for details.
Metadata
Release files for flask-allowed-hosts 1.0.4
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | |
|---|---|---|---|
| flask_allowed_hosts-1.0.4.tar.gz | 5.2 kB | Details |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Reset |
|---|---|---|---|---|
| flask_allowed_hosts-1.0.4-py3-none-any.whl | Python 3 | none | any | Details |
Total release size: 11.2 kB
Release files / flask_allowed_hosts-1.0.4.tar.gz
| Download URL | flask_allowed_hosts-1.0.4.tar.gz |
|---|---|
| Size | 5.2 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
bf130b1ebd26ad067cb347cfe160a9e84862330e6198b2ff00b898aaa8a5e070
|
|
BLAKE2b-256 checksum How to use checksums |
533e1ad6f40cb399615eac47816715e04a04ecf714dc6c97daab53f41415ae15
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/5.0.0 CPython/3.12.2
|
Release files / flask_allowed_hosts-1.0.4-py3-none-any.whl
| Download URL | flask_allowed_hosts-1.0.4-py3-none-any.whl |
|---|---|
| Size | 5.9 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
cfc1f2564c9f8da19bc9117bf07b3044d87cdff384cd670a4c7174890fc0fda5
|
|
BLAKE2b-256 checksum How to use checksums |
63b08876d728b6a0c6c444123aaa3ac70891f8bb26f6df32411de72b1a84038d
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/5.0.0 CPython/3.12.2
|