• 备忘asp.net core使用中间件实现IP白名单访问


    1、**添加中间件MiddleWare**

     1  public class MyMiddleware
     2     {
     3         private readonly RequestDelegate _next;
     4         private readonly ILogger<MyMiddleware> _logger;
     5         private readonly string _safelist;
     6         public MyMiddleware(RequestDelegate next, ILogger<MyMiddleware> logger, string safelist)
     7         {
     8             _safelist = safelist;
     9             _next = next;
    10             _logger = logger;
    11         }
    12         public async Task Invoke(HttpContext context)
    13         {
    14             var remoteIp = context.Connection.RemoteIpAddress;
    15             FileStream fs = new FileStream("ip.txt", FileMode.OpenOrCreate);
    16             //获得字节数组
    17             byte[] data = System.Text.Encoding.Default.GetBytes(DateTime.Now + "ip" + ":" + remoteIp);
    18             //开始写入
    19             fs.Write(data, 0, data.Length);
    20             //清空缓冲区、关闭流
    21             fs.Flush();
    22             fs.Close();
    23             _logger.LogDebug("Request from Remote IP address: {RemoteIp}", remoteIp);
    24             string[] ip = _safelist.Split(';');
    25             var bytes = remoteIp.GetAddressBytes(); var badIp = true;
    26             for (int i = 0; i < ip.Length; i++)
    27 
    28             {
    29                 var testIp = IPAddress.Parse(ip[i]);
    30                 if (testIp.GetAddressBytes().SequenceEqual(bytes))
    31                 { badIp = false; break; }
    32             }
    33             if (badIp)
    34             {
    35                 _logger.LogWarning($"Forbidden Request from Remote IP address: {remoteIp}");
    36                 context.Response.StatusCode = StatusCodes.Status403Forbidden;
    37                 await context.Response.WriteAsync($"Forbidden Request from Remote IP address: {remoteIp}");
    38 
    39                 return;
    40             }
    41             await _next.Invoke(context);
    42         }
    43     }

    2.**在statr up中使用中间件(可以将IP地址放在appsetting.json中多个ip使用";"分隔)** 

     1 app.UseMiddleware(Configuration["WhiteIPList"]); 

  • 相关阅读:
    第01组-Alpha冲刺总结
    pypy windows安装scrapy
    Python:pip无法使用No module named '_sysconfigdata_m_linux_x86_64-linux-gnu'
    Jenkins+Ansible+Gitlab:通过curl自动推送文件&gitlab自动触发构建
    zabbix安装及问题小结
    虚拟机中的jenkins无法访问&Nginx配置
    centos7 安装gitlab及简单配置
    kerberos&LDAP实现免密码登录搭建
    kerberos&ssh 原理、免密登录搭建
    自启动脚本/etc/rc.local文件
  • 原文地址:https://www.cnblogs.com/zhangdongwei/p/14803509.html
Copyright © 2020-2023  润新知