通过 web.config 设置拒绝目录中的所有文件

2024-05-02

作为测试,我尝试使用 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 授权 and IIS URL 授权。有关于此的详细摘要位于http://www.iis.net/learn/manage/configuring-security/understanding-iis-url-authorization#Differences http://www.iis.net/learn/manage/configuring-security/understanding-iis-url-authorization#Differences

简而言之,默认情况下 ASP.NET 与 web.config 发生的情况是,它仅应用allow and deny由托管处理程序处理的文件的规则。

.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>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

通过 web.config 设置拒绝目录中的所有文件 的相关文章

随机推荐