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

原文地址: https://www.cnblogs.com/stulzq/p/8987632.html


 
 

.NET社区新闻,深度好文,欢迎访问公众号文章汇总 http://www.csharpkit.com

640?wx_fmt=jpeg

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值