栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

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

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

.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(Configuration.GetSection("SafeIpList"));
  1. 新建一个中间件写入以下代码
    public class SafeListMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly ILogger _logger;
        private SafeIpList _SafeIpList = null;

        public SafeListMiddleware(
            RequestDelegate next,
            ILogger logger,
            IOptionsMonitor 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();

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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/306139.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号