views:

35

answers:

3

I need to secure access to all pages in a .NET webapp - EXCEPT requests from:

  • local network (the network IIS is running on)
  • IPs listed/netmasks listed in a database

all other requesets should be redirected to a login form

I was thinking in the direction of a HttpModule - but never wrote one. Can anyone provide any ideas to this?

Thank you!

A: 

I'd rather build a global authentication method to check against the ip. Calling this function in the OnInit or OnLoad of your MasterPage or your own implementation of System.Web.Page should do the trick.

If the user has to login, set some randomly generated id in your session to check against (saving the random id to your database and session). In your global authentication method, you can now check for the valid ip range or a valid (database-registred) session token.

schaermu
A: 

Using a HttpModule would be the best way to do this. You could use this to catch any requests before the page executes and redirect to the login form if required.

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;
        }
    }

You'll also need to modify web.config and add a reference to the module:

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

This code would also need some modification to ensure that users who are logged in are not redirected back to the login page, but it should be enough to get you started.

Mun
A: 

Here is a custom authorization module based on regular expressions: http://code.google.com/p/talifun-web/wiki/RegexUrlAuthorizationModule

It should be easy to refactor to your needs.

Taliesin