3

I am trying to secure a folder under my project that just has some static files, a combination of .htm and .js files. I have tried creating a custom HttpHandler like:

public class StaticFilesHttpHandler : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        if (context.Request.IsAuthenticated)
        {
            // continue with the request
        }
        else
        {
            throw new HttpResponseException(HttpStatusCode.Unauthorized);
        }
    }

    public bool IsReusable => false;
}

Then register it to be used with a route via Route.Config

routes.RouteExistingFiles = true;
routes.Add("helpRoute", new Route("folder/*.htm", new StaticFilesRouteHandler ()));

and a route handler to provide the

public class StaticFilesRouteHandler : IRouteHandler
{
    public IHttpHandler GetHttpHandler(RequestContext context)
    {
        return new StaticFilesHttpHandler ();
    }
}

and also via web.config under system.webServer

<handlers>
  <add name="StaticFileHandler" verb="GET" path="~/help/default.htm" type="StaticFilesHttpHandler "/>
</handlers>

Files in the folder are provided by a 3rd party. I am to call a function inside a js file in the folder which then redirects the user to a proper .htm file inside it's sub structure. I do not want users to be able to type the url and access any of the files. What am I doing wrong?

Guranjan Singh
  • 734
  • 2
  • 7
  • 24
  • See [MVC website - how to prevent access to static files](https://stackoverflow.com/q/36425635/) – NightOwl888 Oct 17 '17 at 08:23
  • @NightOwl888 that gets rid of all access to those files. I still want users to be able to access those files but only if they're authorized. – Guranjan Singh Oct 17 '17 at 16:35
  • You are right. You should see [How do I protect static files with ASP.NET form authentication on IIS 7.5?](https://stackoverflow.com/questions/2903292/how-do-i-protect-static-files-with-asp-net-form-authentication-on-iis-7-5) instead. – NightOwl888 Oct 17 '17 at 17:18
  • That gives access denied when I try to access the directory even when I'm logged in. I think the reason is because we're using .NET Identity for authentication. – Guranjan Singh Oct 17 '17 at 18:57

1 Answers1

1

can you change the type to TransferRequestHandler and make sure your path is correct.

<handlers>
  <add name="StaticFileHandler" verb="GET" path="~/help/default.htm" type="TransferRequestHandler" />
</handlers>

in your global.asax file you can access the request in Application_BeginRequest to verify if the request is authenticated or not.

Charlie Ng
  • 640
  • 5
  • 11