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.

4 Comments

  • I think you will also need to configure the ISAPI for *.zip and *.pdf to aspnet_isapi.dll to ensure that ASP.Net gets to process the request, otherwise IIS will just treat it as a normal file and allow the user to download it.

  • I'm using something similar to get my Silverlight app to display PDF files. I'm using the context.User.Identity.IsAuthenticated approach and it works fine on the ASP dev server hosted by VS.
    My issue is that I can't get context.User.Identity.IsAuthenticated to true once I deploy my solution the IIS server in Windows 2008.

    Would you happen to have any insight on this? Maybe it's jsut a configuration to set to IIS.

  • As written, the file would never be downloaded. You need to code pass along the file if the user is authenticated.

  • Authenticated file access using http handler.. Keen :)

Comments have been disabled for this content.