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.AspNetCore

2.配置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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM