2009-12-22 79 views
0

登入我需要確保獲得在.NET Web應用程序的所有頁面 - 除了從請求:ASP.NET:需要根據子網掩碼

  • 本地網絡(網絡IIS上運行)
  • IP地址在數據庫中列出的上市/掩碼

所有其他requesets應該被重定向到一個登錄表單

我是在一個HTTP模塊的方向思考 - 但從來沒有寫過一個。 任何人都可以提供任何想法嗎?

謝謝!

+0

我建議您應該在防火牆中執行此操作如果您確實有權訪問您的服務器防火牆。 – 2009-12-22 10:12:44

回答

0

使用HttpModule將是最好的方法。您可以使用它在頁面執行前捕獲任何請求,並在需要時重定向到登錄表單。

public class SecurityModule : IHttpModule 
{ 
    private HttpApplication m_HttpApplication; 

    public void Init(HttpApplication context) 
    { 
     m_HttpApplication = context; 
     m_HttpApplication.PreRequestHandlerExecute += new EventHandler(OnPreRequestHandlerExecute); 
    } 

    public void Dispose() 
    { 
     // Do Nothing 
    } 

    private void OnPreRequestHandlerExecute(object sender, EventArgs e) 
    { 
     // Get IP address 
     string ipAddress = m_HttpApplication.Context.Request.UserHostAddress; 

     // Check if the IP address requires login 
     bool requiresLogin = ValidateIpAddress(ipAddress); 

     // Redirect if required 
     if (requiresLogin) 
      Response.Redirect("~/Login.aspx", true); 
     } 

     private bool ValidateIpAddress(string ipAddress) 
     { 
      // This method would check that the IP address is from the local 
      // network or in the database and return true or false accordingly. 

      return false; 
     } 
    } 

您還需要修改web.config文件並添加引用到模塊:

<httpModules> 
    <add name="SecurityModule" type="MyApp.SecurityModule, MyApp"/> 
</httpModules> 

此代碼也需要做一些修改,以確保在已登錄的用戶誰不重定向回到登錄頁面,但它應該足以讓你開始。

0

我寧願建立一個全球認證方法來檢查IP。在你的MasterPage的OnInit或OnLoad中調用這個函數或者你自己的System.Web.Page的實現應該可以做到。

如果用戶必須登錄,請在會話中設置一些隨機生成的ID來檢查(將隨機ID保存到數據庫和會話中)。在您的全局身份驗證方法中,您現在可以檢查有效的IP範圍或有效的(數據庫註冊的)會話令牌。