Asp.net

通過 web.config 設置拒絕目錄中的所有文件

  • May 6, 2016

作為測試,我正在嘗試使用 web.config 通過以下方式控制安全性:

  1. 拒絕訪問目錄中的所有文件,特定文件除外
  2. 允許訪問目錄中的所有文件,特定文件除外

所以我設置 web.config 如下:

<?xml version="1.0" encoding="utf-8"?>
<configuration>

 <!-- Deny access to all files in a directory, except for a specific file -->
 <location path="NonAccessibleDirectory">
   <system.web>
       <authorization>
         <deny users="?"/>
         <deny users="*"/>
       </authorization>
   </system.web>
 </location>

 <location path="NonAccessibleDirectory/AccessibleFile.html">
   <system.web>
       <authorization>
         <allow users="?"/>
         <allow users="*"/>
       </authorization>
   </system.web>
 </location>

 <!-- Allow access to all files in a directory, except for a specific file -->
 <location path="AccessibleDirectory/NonAccessibleFile.html">
   <system.web>
       <authorization>
         <deny users="?"/>
         <deny users="*"/>
       </authorization>
   </system.web>
 </location>

 <system.web>
   <compilation debug="true" targetFramework="4.5" />
   <httpRuntime targetFramework="4.5" />
 </system.web>

</configuration>

正如預期的那樣:

  • 如果我瀏覽到不可訪問的目錄並且未指定文件,則會拒絕訪問
  • 如果我瀏覽到可訪問的目錄並且沒有指定文件,我可以看到文件列表

我遇到的問題是:

  • 如果我瀏覽到不可訪問的目錄並指定一個文件,我可以查看它,並且我希望不會被授予訪問權限
  • 如果我瀏覽到可訪問目錄並通過 web.config 指定一個我拒絕訪問的文件,我仍然可以查看它,並且我希望不會被授予訪問權限

艾米我配置錯了嗎?

您可能遇到了ASP.NET URL AuthorizationIIS URL Authorization之間的區別。對此的詳細摘要位於http://www.iis.net/learn/manage/configuring-security/understanding-iis-url-authorization#Differences

簡而言之,預設情況下 ASP.NET 與 web.config 發生的情況是,它僅將允許拒絕規則應用於託管處理程序處理的文件。

.txt 和 .html 文件等文件由 IIS 而不是 ASP.NET 處理,因此授權規則不適用於它們。

您可以通過將其添加到您的主 web.config 以使用 IIS 版本來測試它。

<system.webServer>
   <modules>
       <remove name="UrlAuthorization" />
       <add name="UrlAuthorization" type="System.Web.Security.UrlAuthorizationModule"  />
   </modules>
</system.webServer>

我使用相同的安全性以及相同的目錄和文件對此進行了測試,並且一切似乎都有效

如果您使用其他身份驗證方法(例如表單),則更完整的版本可能是這個

<system.webServer>
   <modules>
       <add name="FormsAuthenticationModule" type="System.Web.Security.FormsAuthenticationModule" />
       <remove name="UrlAuthorization" />
       <add name="UrlAuthorization" type="System.Web.Security.UrlAuthorizationModule"  />
       <remove name="DefaultAuthentication" />
       <add name="DefaultAuthentication" type="System.Web.Security.DefaultAuthenticationModule" />
   </modules>
</system.webServer>

引用自:https://stackoverflow.com/questions/37078383