Skip to main content

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

To limit access to your routes using flask-allowedhosts follow these simple steps:

  1. Import the limit_hosts decorator from flask_allowedhosts.
  2. Define the list of allowed hosts.
  3. Apply the @limit_hosts decorator to the desired endpoint(s).
from flask import Flask, request, jsonify
from flask_allowedhosts import limit_hosts

app = Flask(__name__)

ALLOWED_HOSTS = ['127.0.0.1', 'localhost']

def on_denied():
    return "Unauthorized access", 401

@app.route("/api/greet")
@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)

Now only the allowed hosts set in ALLOWED_HOSTS can access the protected endpoint(s). Requests from other hosts will receive a 403 Forbidden error.

Arguments

  • allowed_hosts: List[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 is None, 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.

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

flask_allowedhosts-1.3.0.tar.gz (3.9 kB view hashes)

Uploaded Source

Built Distribution

flask_allowedhosts-1.3.0-py3-none-any.whl (4.6 kB view hashes)

Uploaded Python 3

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page