Agha Usman

Lives in Karachi (Pakistan) and work for Ciber Strategies

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.

Posted: May 08 2009, 03:21 AM by aghausman12 | with 4 comment(s)
Filed under: , ,

Comments

Authenticated File Access using HTTP Handler. - Agha Usman said:

Pingback from  Authenticated File Access using HTTP Handler. - Agha Usman

# May 7, 2009 5:55 PM

TipsOnLips.net said:

HTTP Handlers and Modules in ASP.NET

# May 7, 2009 7:44 PM

Robert said:

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.

# July 9, 2009 9:14 AM

R4cOOn said:

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.

# August 10, 2009 5:34 AM
Leave a Comment

(required) 

(required) 

(optional)

(required)