-->

aspnet static file access with authentication

2019-05-20 00:48发布

问题:

In my application folder I have virtual application QA. There is a folder "help" which contains html and other static files. QA is using form authentication.

All files in help folder are accessible without authentication (for example, www.mypage.com/QA/help/test.html). I need to change this so that if user acces files in help folder (html files or any other static files) then user is redirecet to login page. I was googling and the ony thing I have found is that this is something with Static file handling and mapping to asp. I am using IIS 6.

I have tried to add line like this

< add name="StaticHandler" type="System.Web.StaticFileHandler" path="*.html" verb="*" validate="true" /> 

to my web.config (that is in QA folder), but it doesn't help. Actually, I do not understand this line and also I am new to web.config file administrating. I also tried to put all static files from help folder into QA, but it also doesn't help.

回答1:

Make sure you have added a config file to the directory that contains your static files that you want protected from anonymous users like so (this means you will have a second web.config file in the directory you are trying to protect). Which will deny any anonymous users (that is what the does).

<configuration>
    <appSettings/>
    <connectionStrings/>
    <system.web>
      <authorization>
        <deny users="?"/>
      </authorization>
    </system.web>
</configuration>

IIS is serving your static files outside of the ASP.net pipeline. Besides adding the declaration you have added System.Web.StaticFileHandler you need to map the extension in IIS. In order to ensure that your .htm or .html files are passed through ASP.net and therefore authenticated.

In your root web .config file add

<system.web>
   <httpHandlers>
      <add path="*.html" verb="*" type="System.Web.StaticFileHandler" />
   </httpHandlers>

Then you need to perform some operation in IIS. These directions apply to IIS 6.0

  1. Open IIS Manager
  2. Right click on your website and select properties
  3. Click Home Directory -> Configuration (displays application extensions etc). You will need the path from a mapped extension already in use by asp.net. The best way to get this is to find an already mapped asp.net extension in the list like .aspx or.ascx, click Edit and copy the Executable path. The path should end in aspnet_isapi.dll.
  4. Click Add
  5. Paste in the previous executable path and the extension (in your case .html).
  6. Repeat this process for any other file types you want handled by the ASP.net runtime.