1

We have asp.net MVC & angular application. We are using identityserver3 for access control to the application. Everything is working as expected, except one thing. Unauthorized users still have access to static content of the application.

Is there any way to deny access to those files before user log in ?

piowtarn
  • 73
  • 1
  • 10

3 Answers3

3

Here is the link to the great post which led me to the solution => Intercepting file requests

Steps I've taken to solve my problem:

  1. Added this line to my webconfig file. This will make sure that js files request wil not be processed by handler.

     <system.webServer>
        <handlers>
           <add name="JSFileHandler" path="*.js" verb="GET"
               type="System.Web.Handlers.TransferRequestHandler"      
               preCondition="integratedMode,runtimeVersionv4.0" />
        </handlers>
    </system.webServer>
    
  2. Register route.

        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    
        routes.RouteExistingFiles = true;
        routes.MapRoute(
            "staticfiles"
            , "{*src}"
            , new { Controller = "Main", action = "GetJS" }
            , new { src = @"(.*?)\.(js)" }                     // URL constraints
        );
    
  3. Return file from controllers action

    public ActionResult GetJS()
    {
    
       var path = this.Url.RouteUrl("staticfiles");
       return File(path,
           System.Net.Mime.MediaTypeNames.Application.Octet,
           Path.GetFileName(path));
    }
    
piowtarn
  • 73
  • 1
  • 10
1

You can add this to your web.config

<location path="your/path/tostaticfiles">       
  <system.web>
      <authorization>                
        <deny users="?" /> //Denies unauthorized users
      </authorization>
  </system.web>
</location>
andreasnico
  • 1,478
  • 14
  • 23
  • With form authentications it works like a charm but in this case it does not seems to have any effect. – piowtarn Mar 31 '16 at 13:29
  • In addition, this will only work for files whose types are mapped to .NET in the IIS handler mappings. jpg files, for instance, are not by default and IIS will serve them up before routing the request to .NET. – esmoore68 Mar 31 '16 at 17:00
1

Apart from the location section you also need to indicate IIS that ASP.NET will process these files (runAllManagedModulesForAllRequests="true").

Next to (sibling of system.web node):

  <location path="Scripts">
    <system.web>
      <authorization>
        <deny users="?" />
      </authorization>
    </system.web>
  </location>

Under system.webServer node:

<modules runAllManagedModulesForAllRequests="true">

Note: use users="*" instead of users="?" if you don't want to let any user access your files. In my case I did that to prevent access to my JS files and I serve them using bundles.

Francisco Goldenstein
  • 13,299
  • 7
  • 58
  • 74