A Flask extension to limit access to your routes by using allowed hosts.
Project description
Flask Allowed Hosts
Flask Allowed Hosts is a Flask extension that provides host validation for API endpoints. It allows you to enforce that requests are only accepted from specific hosts, providing an additional layer of security for your Flask application.
Installation
Install the package using pip:
pip install flask-allowedhosts
Getting Started
- Import the check_host decorator from flask_allowedhosts:
from flask import Flask, request, jsonify
from flask_allowedhosts import check_host
- Create a Flask application instance:
app = Flask(__name__)
- Define the list of allowed hosts:
ALLOWED_HOSTS = ['127.0.0.1', 'localhost']
- Apply the
@check_host
decorator to the desired endpoint(s):
@app.route("/api")
@check_host(allowed_hosts=ALLOWED_HOSTS)
def greet_endpoint():
name = request.args.get("name", "Friend")
greeting = {"greeting": f"Hello There {name}!"}
return jsonify(greeting), 200
The default value for allowed_hosts
is an empty list, which means requests from all hosts are allowed.
- Run the Flask application:
from flask import Flask, request, jsonify
from flask_allowedhosts import check_host
app = Flask(__name__)
ALLOWED_HOSTS = ['127.0.0.1', 'localhost']
@app.route("/api")
@check_host(allowed_hosts=ALLOWED_HOSTS)
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)
Now only the allowed hosts can access the protected endpoint(s). Requests from other hosts will receive a 403 Forbidden error.
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.
Project details
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Hashes for flask_allowedhosts-1.1.0-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 7c4319b02aec1d7cec9a26080494697972f674d9cc8aa7379d1e4678f961d38f |
|
MD5 | b605e248f95c3716f017926094324843 |
|
BLAKE2b-256 | cf48fbf81a4eb67e0c78bf85f289e3a8ef309d38afb5bfe8a531c8bc3f676fc5 |