.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,有高手的話,請指點一二。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM