piowtarn
piowtarn

Reputation: 71

prevent access to static content of asp.net - mvc app

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 ?

Upvotes: 1

Views: 2403

Answers (3)

Francisco Goldenstein
Francisco Goldenstein

Reputation: 13767

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.

Upvotes: 1

piowtarn
piowtarn

Reputation: 71

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));
    }
    

Upvotes: 3

andreasnico
andreasnico

Reputation: 1488

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>

Upvotes: 1

Related Questions