Authenticated File Access using HTTP Handler.
In this post I will explain you how authenticate the request directly coming to access a file that is downloadable. some thing like *.pdf or *.zip.
Mostly, people make it working by creating an *.aspx page and then write binary of that file in Response.WriteFile. So, user will have no idea where the file is coming from. now this is the fair approach but what if somebody, somehow know the path of downloadable files.
So, to stop the un authenticated access to our files, we will first create a session enable HTTP handler.
public class MyHttpHandler : IHttpHandler, IReadOnlySessionState
{
public void ProcessRequest(HttpContext context)
{
if (context.Session["userId"] == null)
// I am using a session variable you can also use context.User.Identity.IsAuthenticated
{
context.Response.Redirect("/login.aspx?retUrl=" + context.Request.RawUrl);
//Redirecting to the login page ... alternatively you can also set context.Response.StatusCode
}
}
public bool IsReusable
{
get { return false; }
}
}
Now, once we have created that. Let me register my newly creater handler for *.zip and *.pdf files in web.config.
<httpHandlers>
<add verb="*" path="*.zip" type="LearningApp.MyHttpHandler, LearningApp"/>
<add verb="*" path="*.pdf" type="LearningApp.MyHttpHandler, LearningApp"/>
</httpHandlers>
That’s it. If you want more file types to be authenticated add more verbs in handler section of HttpHandler.
Don’t try to put *.* : That can create some serious problem because then each of your *.aspx, *asmx and all your logic stuff will need authentication.