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

徘徊边缘 提交于 2019-12-24 15:20:50

问题


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 ?


回答1:


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



回答2:


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>



回答3:


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.



来源:https://stackoverflow.com/questions/36334427/prevent-access-to-static-content-of-asp-net-mvc-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!