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.

This article is part of the GWB Archives. Original Author: Agha Usman Ahmed

New on Geeks with Blogs

  • We Won The One Award I Actually Care About

    Full Scale made the Inc. 5000 for the fifth year straight, the 12th listing across my three companies. Here is why the one award you cannot buy is worth stopping for.

  • Your Customers Build the Features Now

    I let a tool I liked sit dead for a year rather than build the features I wanted. An MCP server meant I never had to, and your customers can do the same to your product.

  • Get the Size of a Directory in Linux the Easy Way

    du -sh for the quick answer, ncdu for the cleanup, df for the disk itself: every command for checking directory size in Linux, plus why du and df never agree.

  • Vim Search and Replace: The Ultimate Guide

    One :%s command replaces every match in a file before a find dialog would even open. The Vim substitute patterns worth the muscle memory: flags, ranges, capture groups, and multi-file edits.