代码之家  ›  专栏  ›  技术社区  ›  reinhard

ASP.NET:需要基于netmask登录

  •  0
  • reinhard  · 技术社区  · 16 年前

    我需要确保对.NET webapp中所有页面的访问安全-以下请求除外:

    • 本地网络(运行IIS的网络)
    • 数据库中列出的IP列表/网络掩码

    所有其他请求都应重定向到登录表单

    我一直在思考httpmodule的发展方向,但从来没有写过。 有人对此有什么想法吗?

    谢谢您!

    3 回复  |  直到 16 年前
        1
  •  0
  •   Mun    16 年前

    使用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>
    

    此代码还需要进行一些修改,以确保登录的用户不会被重定向回登录页面,但这应该足以让您开始。

        2
  •  0
  •   schaermu    16 年前

    我宁愿构建一个全局身份验证方法来检查IP。在母版页的OnInit或OnLoad中调用此函数或在System.Web.Page的实现中调用此函数应该可以做到这一点。

    如果用户必须登录,请在会话中设置一些随机生成的ID进行检查(将随机ID保存到数据库和会话中)。在全局身份验证方法中,现在可以检查有效的IP范围或有效的(数据库注册的)会话令牌。

        3
  •  0
  •   Taliesin    16 年前

    下面是基于正则表达式的自定义授权模块: http://code.google.com/p/talifun-web/wiki/RegexUrlAuthorizationModule

    根据需要重构应该很容易。

    推荐文章