UrlFirewall is a lightweight, fast filtering middleware for http request urls.It supports blacklist, whitelist mode.Supports persisting filter rules to any media.You can use it in webapi, gateway, etc.
English(Current) | 中文
Install-Package UrlFirewall.AspNetCore
public void ConfigureServices(IServiceCollection services)
{
services.AddUrlFirewall(options =>
{
options.RuleType = UrlFirewallRuleType.Black;
options.SetRuleList(Configuration.GetSection("UrlBlackList"));
options.StatusCode = HttpStatusCode.NotFound;
});
services.AddMvc();
//...
}
The order of middleware must be at the top most.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
//Configure url firewall middleware. Top most.
app.UseUrlFirewall();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseMvc();
}
In appsettings.json/appsettings.Devolopment.json create a section.
{
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
}
},
"UrlBlackList": [
{
"Url": "/api/cart/add",
"Method": "All"
},
{
"Url": "/api/cart/del",
"Method": "Post"
},
{
"Url": "/api/cart/list",
"Method": "Get"
},
{
"Url": "/api/product/*",
"Method": "All"
}
]
}
The url field is the http request path we need to match.It supports wildcard *
and ?
.The *
represents an arbitrary number of arbitrary characters. The ?
representative matches any one arbitrary character
Now,you access /api/cart/add
etc.Will be get 404.Enjoy yourself.
If you want to implement validation logic yourself, or You want to verify by getting data from the database, redis etc.You can implement the IUrlFirewallValidator
interface.Then you can replace the default implementation with the AddUrlFirewallValidator
method.
e.g:
services.AddUrlFirewall(options =>
{
options.RuleType = UrlFirewallRuleType.Black;
options.SetRuleList(Configuration.GetSection("UrlBlackList"));
options.StatusCode = HttpStatusCode.NotFound;
}).AddUrlFirewallValidator<CustomValidator>();