.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,有高手的话,请指点一二。

 

转载于:https://www.cnblogs.com/happyframework/archive/2013/05/05/3054417.html

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值