背景
为了增强系统的安全,很多信息系统都提供了“IP限制”功能。功能虽然简单,但是从业五年来从来没有是实现过,因此就以博文的形式记录下来。
思路
实现应该很简答,功能可以分解为如下这三个问题:
- 判断当前请求是否应用IP限制,有些请求不用应用IP限制的。
- 当前客户IP是否包含在限制列表中。
- 如何以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 }
实现细节
- this.Request.UserHostAddress的格式为“127.0.0.1”。
- this.Request.Url.AbsolutePath的格式为“/Tests/GetIp.aspx”,
- 具体限制IP列表和排除地址列表的存储可以自己酌情实现。
备注
对应黑客知识,我并不了解,黑客是不是很容易模拟客户端IP,有高手的话,请指点一二。