Sunday, June 24, 2012

Restrict File download to unauthorized users

Following code is for allowing only the registered(logged in) users to download files
Step 1: Create a file Handler.ashx and write the following code. Since I am not using form authentication, I am checking the session variables which are set once the user successfully logs in. Please note the implementation of IRequiresSessionState interface, this is because the HttpHandler cannot access session parameters on its own.
<%@ WebHandler Language="C#" Class="Handler" %> using System; using System.Web; using System.Web.Security; using System.Web.SessionState; public class Handler : IHttpHandler,IRequiresSessionState { public void ProcessRequest (HttpContext context) { try { if (context.Session["user"] != null) { string filename = context.Request.QueryString["File"]; //Validate the file name and make sure it is one that the user may access context.Response.Buffer = true; context.Response.Clear(); context.Response.AddHeader("content-disposition", "attachment; filename=" + filename); context.Response.ContentType = "octet/stream"; context.Response.WriteFile("~/downloads/" + filename); } else context.Response.Redirect("~/Default.aspx"); } catch (NullReferenceException ex) { context.Response.Redirect("~/Default.aspx"); } catch (System.Exception ex) { context.Response.Write(ex.ToString()); } } public bool IsReusable { get { return true; } } }
Step 2: There is a file titled Default.aspx from which users log in into the system and sets the session variable
protected void Button1_Click(object sender, EventArgs e) { //validation related code goes here Session["user"] = "TEST"; Response.Redirect("~/downloads.aspx"); }
Step 3: The html code in downloads.aspx
<a href="Handler.ashx?File=annex8.pdf">Click Here</a>

Further Reading
Here as well

1 comment:

Unknown said...

Hi,usable e-business websites; websites that not only contain up-to-date, effective information that is easy to find Web Design Cochin, but sites that actually make it easy for users to do all the tasks that they have come to the site to achieve.thanks................