Saturday, October 03, 2009 11:38 AM
Tanzim Saqib
Quickly Secure Your Site Using HttpModule
You have a top secret site hosted on the web and you want to demo it to certain people only. There may be several ways to do it. I wanted to do it under 5 minutes. I created a HttpModule to redirect to a login page. That page will validate against an XML file, which is basically list of username/password like below:
<?xml version="1.0" encoding="utf-8" ?>
<allowed>
<user name="saqib" password="dontknow" />
<user name="tanzim" password="nopassword" />
</allowed>
A HttpModule is pluggable version of Global.asax. The reason why I am calling this because it can be just installed in web.config like the following and has capability to interact with the ASP.NET events like the Global.asax.
<httpModules>
<add type="RedsideSecurity" name="RedsideSecurity" />
</httpModules>
HttpModules have full control over HTTP requests, so the HttpModule I created can intercept the requests can authorize depending on the cookie present in the browser. On Init of the module, I registered a delegate to the BeginRequest event, meaning during the journey through ASP.NET pipeline, this delegate is going to be invoked upon beginning of the request. I checked cookies and if it is not valid, showed link to SecureLogin.aspx page which will display the user/password inputs.
public void Init(HttpApplication context)
{
context.BeginRequest += (sender, args) =>
{
var path = context.Request.Path.ToLowerInvariant();
if (path != "/securelogin.aspx")
{
var cookie = context.Request.Cookies.Get(RED_SIDE_COOKIE_NAME);
if (cookie == null
|| cookie.Value == string.Empty
|| Convert.ToDateTime(cookie.Value) > DateTime.Now.AddMinutes(COOKIE_TIMEOUT_MINUTES))
{
context.Response.Write("<span style=\"color: red; font-weight: bold;\""
+ ">Sir, your ID please.</span> <a href=\"securelogin.aspx\">Login</a>");
context.Response.End();
}
}
};
}
Code for SecureLogin.aspx is easy as well. Try matching the credential supplied by user from the XML file, set cookie if authorized and redirect to default.aspx.
protected void btnLogin_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
var cookie =
new HttpCookie(RedsideSecurity.RED_SIDE_COOKIE_NAME, DateTime.Now.ToString());
cookie.Expires = DateTime.Now.AddMinutes(RedsideSecurity.COOKIE_TIMEOUT_MINUTES);
Response.Cookies.Set(cookie);
Response.Redirect("default.aspx");
}
}
protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
{
var path = Server.MapPath("~/App_Data/RedsideSecurity.xml");
var allowedUsers = XElement.Load(path);
var user = (from u in allowedUsers.Elements("user")
where u.FirstAttribute.Value == txtUsername.Text
&& u.LastAttribute.Value == txtPassword.Text
select u).FirstOrDefault();
args.IsValid = user != null;
}
Filed under: ASP.NET