zoukankan      html  css  js  c++  java
  • .NET:在ASP.NET中如何进行IP限制

    背景

    为了增强系统的安全,很多信息系统都提供了“IP限制”功能。功能虽然简单,但是从业五年来从来没有是实现过,因此就以博文的形式记录下来。

    思路

    实现应该很简答,功能可以分解为如下这三个问题:

      1. 判断当前请求是否应用IP限制,有些请求不用应用IP限制的。
      2. 当前客户IP是否包含在限制列表中。
      3. 如何以AOP的形式应用IP限制

    1和2可以抽象为一个接口

     1 using System;
     2 
     3 namespace IpLimit.Codes
     4 {
     5     interface IIpLimitService
     6     {
     7         bool IsInExcludeUrl(string url);
     8         bool IsInLimit(string ip);
     9     }
    10 }

    3可以用IHttpModule实现

     1 using System;
     2 using System.Collections.Generic;
     3 using System.Linq;
     4 using System.Web;
     5 
     6 namespace IpLimit.Codes
     7 {
     8     public sealed class IpLimitModule : IHttpModule
     9     {
    10         public void Dispose()
    11         {
    12 
    13         }
    14 
    15         public void Init(HttpApplication context)
    16         {
    17             context.BeginRequest += this.OnBeginRequest;
    18         }
    19 
    20         private void OnBeginRequest(object sender, EventArgs args)
    21         {
    22             var ipLimitService = new IpLimitService();
    23             var clientIp = HttpContext.Current.Request.UserHostAddress;
    24             var requestUrl = HttpContext.Current.Request.Url;
    25 
    26             if (ipLimitService.IsInExcludeUrl(requestUrl.AbsolutePath))
    27             {
    28                 return;
    29             }
    30 
    31             if (ipLimitService.IsInLimit(clientIp))
    32             {
    33                 HttpContext.Current.Response.Redirect("IpLimit.html");
    34             }
    35         }
    36     }
    37 }

    实现细节

      1. this.Request.UserHostAddress的格式为“127.0.0.1”。
      2. this.Request.Url.AbsolutePath的格式为/Tests/GetIp.aspx”,
      3. 具体限制IP列表和排除地址列表的存储可以自己酌情实现。

    备注

    对应黑客知识,我并不了解,黑客是不是很容易模拟客户端IP,有高手的话,请指点一二。

  • 相关阅读:
    【Codeforces 923A】Primal Sport
    【Codeforces 924C】Riverside Curio
    【Codeforces 682C】Alyona and the Tree
    【Codeforces 1118D1】Coffee and Coursework (Easy version)
    【Codeforces 493C】Vasya and Basketball
    【Codeforces 598D】Igor In the Museum
    js 时间格式化
    C#自定义规则对比两个集合的对象是否相等
    VUE的组件DEMO
    js 去掉指定符号的字符串做法
  • 原文地址:https://www.cnblogs.com/happyframework/p/3054417.html
Copyright © 2011-2022 走看看