I need to secure access to all pages in a .NET webapp - EXCEPT requests from:
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!
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.