【问题标题】:web.config - how to allow specific IP regardsless of <deny users="*" />web.config - 如何允许特定 IP 而不管 <deny users="*" />
【发布时间】:2015-11-10 15:04:24
【问题描述】:

我想在我的 web.config 中使用以下内容保护目录中的文件 - 但我也想破例,这样一个特定的 IP 就可以在不登录的情况下访问该内容。

<configuration>
<system.web>
    <authorization>

        <allow roles="Role 1" />
        <allow roles="Role 2" />
        <deny users="*" />
    </authorization>
</system.web>

如何做到这一点?

【问题讨论】:

  • 我已经查看了 ipsecurity,但我想结合这两种方法,我希望它是这样的:如果请求来自一个特定的 IP,则始终会从所有其他 IP 授予访问权限用户必须登录并且是授权部分中定义的组之一的成员

标签: asp.net iis web-config


【解决方案1】:

没有允许这样做的内置方法,但我认为您应该能够编写一个提供“IP 身份验证”的快速模块,并且除了其他身份验证模块之外,您还可以使用该模块以及提供的任何一个身份将起作用。

例如,这里有一个简单的示例:

public class IPAuthenticationModule : IHttpModule {

    private IPAddress[] ipAddresses = {};
    public void Dispose() {
    }

    public void Init(HttpApplication context) {
        string s = ConfigurationManager.AppSettings["ipAddresses"];
        if (!string.IsNullOrWhiteSpace(s)) {
            this.ipAddresses = s.Split(',').Select((ip) => IPAddress.Parse(ip.Trim())).ToArray();
        }

        context.AuthenticateRequest += OnContextAuthenticateRequest;
    }

    private void OnContextAuthenticateRequest(object sender, EventArgs e) {
        HttpApplication app = (HttpApplication)sender;
        HttpContext context = app.Context;
        if (context.User == null) {
            string clientIP = context.Request.UserHostAddress;
            IPAddress clientIPAddress = IPAddress.Parse(clientIP);
            if (this.ipAddresses.Contains(clientIPAddress)) {
                context.User = new GenericPrincipal(
                    new GenericIdentity(clientIP, "Basic"),
                    new string[] { "IPAddressRole" });
            }
        }
    } 
}

然后在您的 web.config 中配置模块以及允许的 ipAddresses,例如:

  <appSettings>
    <add key="ipAddresses" value="127.0.0.1,::1"/>
  </appSettings>
  <system.webServer>
    <modules>
      <add name="IPAuthenticationModule" type="IPAuthenticationModule, YourDLLName"/>
    </modules>
    <security>
      <authorization>
        <add accessType="Deny" users="?" />
      </authorization>
    </security>
  </system.webServer>

这将允许访问 127.0.0.1,并在身份中注入“IPAddressRole”角色,因此您甚至可以在上面提供访问权限,并根据代表 IP 的角色限制/允许不同的访问级别。它还将使用用户名作为 IP 地址,因此在日志等中您将看到所有内容。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-26
    • 2018-10-13
    • 2011-12-13
    • 2012-04-16
    • 2021-04-17
    • 2016-03-28
    • 2015-11-23
    相关资源
    最近更新 更多