ASP.NET Core 使用UrlFirewall对请求进行过滤
一. 前言
UrlFirewall?是一個開源、輕便的對http請求進行過濾的中間件,可使用在webapi或者網關(比如Ocelot),由我本人編寫,并且開源在github:https://github.com/stulzq/UrlFirewall?歡迎star.
二.UrlFirewall 介紹
UrlFirewall 是一款http請求過濾中間件,可以和網關(Ocelot)搭配,實現屏蔽外網訪問內部接口,只讓內部接口之間相互通訊,而不暴露到外部。它支持黑名單模式和白名單模式,支持自定義http請求響應代碼。具有良好的擴展性,可自己實現驗證邏輯,從數據庫或者Redis緩存等介質實現對規則的檢索。
三.使用
1.從Nuget添加組件到你的ASP.NET Core項目
Install-Package UrlFirewall.AspNetCore2.配置DI
public void ConfigureServices(IServiceCollection services){services.AddUrlFirewall(options =>{options.RuleType = UrlFirewallRuleType.Black;options.SetRuleList(Configuration.GetSection("UrlBlackList"));options.StatusCode = HttpStatusCode.NotFound;});services.AddMvc(); ? ?//...}3.配置中間件
UrlFirewall中間件的位置必須放在第一個
public void Configure(IApplicationBuilder app, IHostingEnvironment env){ ? ?//Configure url firewall middleware. Top most.app.UseUrlFirewall(); ? ?if (env.IsDevelopment()){app.UseDeveloperExceptionPage();}app.UseMvc(); }4.配置規則
根據步驟2,使用的Section名稱·UrlBlackList·我們在appsettings.json/appsettings.Devolopment.json文件中添加以下配置;
{"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"}]}Url 字段表示要攔截的http請求url,支持通配符*和?,*表示匹配任意個數任意字符,?表示匹配一個任意字符。Method表示http請求方法,All代表所有,還有Get Post Delete Put。
四.擴展
如果你想要實現自己的驗證邏輯,或者從數據庫、Redis緩存等介質查詢、獲取數據來進行驗證;你可以實現IUrlFirewallValidator接口,然后調用AddUrlFirewallValidator方法替換默認實現即可。
示例:
services.AddUrlFirewall(options => {options.RuleType = UrlFirewallRuleType.Black;options.SetRuleList(Configuration.GetSection("UrlBlackList"));options.StatusCode = HttpStatusCode.NotFound; }).AddUrlFirewallValidator<CustomValidator>();五.地址
源碼和Demo:https://github.com/stulzq/UrlFirewall
原文地址: https://www.cnblogs.com/stulzq/p/8987632.html
.NET社區新聞,深度好文,歡迎訪問公眾號文章匯總 http://www.csharpkit.com
總結
以上是生活随笔為你收集整理的ASP.NET Core 使用UrlFirewall对请求进行过滤的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 如何在Visual Studio 201
- 下一篇: 为什么 web 开发人员需要迁移到. N