.Net5 使用中间件实现IP过滤

背景

在工作中遇到一个与第三方服务商进行API对接的项目,需要进行IP白名单处理,于是我立马想到使用中间件做IP过滤,在此记录一下

添加中间件

  1. 新建一个SafeIpList类
public class SafeIpList
 {
      public string ip_list_name { get; set; }
}
  1. 在配置文件中配置IP白名单
  "SafeIpList": {
   "ip_list_name ": "127.0.0.1"
 }
  1. 读取注入配置文件中的IP list
  services.Configure<SafeIpList>(Configuration.GetSection("SafeIpList"));
  1. 新建一个中间件写入以下代码
    public class SafeListMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly ILogger<SafeListMiddleware> _logger;
        private SafeIpList _SafeIpList = null;

        public SafeListMiddleware(
            RequestDelegate next,
            ILogger<SafeListMiddleware> logger,
            IOptionsMonitor<SafeIpList> options)
        {
            _SafeIpList = options.CurrentValue;
            _next = next;
            _logger = logger;
        }
              public async Task Invoke(HttpContext context)
        {

            var remoteIp = context.Connection.RemoteIpAddress;
            _logger.LogInformation($"Request from Remote IP address: {remoteIp}");
            string[] ip = _SafeIpList.InternalIPList.Split(';');
            var bytes = remoteIp.GetAddressBytes();
            var badIp = true;
            // 对特定API进行自定义处理
            //if (context.Request.Path.Value.Equals("/api/xx/xxx"))
            //{
            //    ip = _SafeIpList.XXIPList.Split(';');
            //}
            foreach (var address in ip)
            {
                if (address.Equals("*"))
                {
                    badIp = false;
                    break;
                }
                var testIp = IPAddress.Parse(address);
                if (testIp.GetAddressBytes().SequenceEqual(bytes))
                {
                    badIp = false;
                    break;
                }
            }
                  if (badIp)
            {
                _logger.LogInformation(
                    $"Forbidden Request from Remote IP address: {remoteIp}");
                context.Response.StatusCode = (int)HttpStatusCode.Forbidden;
                return;
            }
            await _next.Invoke(context);

        }
    }
  1. 启用中间件
app.UseMiddleware<SafeListMiddleware>();

通过以上简单五步就实现了IP过滤功能

上一篇:【Abp简单使用】模块化(.Net5)


下一篇:.NET5使用Consul注册中心