TOWER ALLOWED HOSTS
Project status & info:
| License | Crates Version | Docs |
|---|---|---|
Tower service which limits request from only specified hosts.
Add as dependencies
In your Cargo.toml file, add tower_allowed_hosts as a dependency:
[]
= "0.12.1"
Usage
Basic
To restrict access to specific basic hosts, you can use the following code:
let tower_layer = new;
Wildcard
If you need wildcard-based host matching, enable the wildcard feature in your Cargo.toml:
[]
= { = "0.12.1", = ["wildcard"] }
You can then restrict hosts using wildcards:
let tower_layer = new;
Regex
If you need regex-based host matching, enable the regex feature in your Cargo.toml:
[]
= { = "0.12.1", = ["regex"] }
You can then restrict hosts using regex patterns:
let tower_layer = new;
Forwarded header
If you wish to also handle Forwarded header than you can extend created AllowedHostLayer with with_forwarded_matcher
let layer = new
.with_forwarded_matcher;
Integrating with a Tower-Compatible Library
After creating the AllowedHostLayer, it can be integrated into any library that supports tower components. Here's an example of how to use this layer in an axum application. You will also need to handle errors properly using HandleErrorLayer:
use ;
use ServiceBuilder;
use AllowedHostLayer;
async
Extension is automatically added after successfully parsing allowed host and allowing host which can be access using
tower_allowed_hosts::Host struct extractor or extension
Extension<Host>. Only when axum feature is enabled you can use Host extractor directly. Otherwise, only Extension<Host> is only valid extractor to extract host