user3279044
user3279044

Reputation: 11

web.config - how to allow specific IP regardsless of <deny users="*" />

I would like to protect files in a directory with the following in my web.config - but I also want to make an exception, so that one specific IP can access the content without logging in.

<configuration>
<system.web>
    <authorization>

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

How can that be done?

Upvotes: 1

Views: 1305

Answers (1)

Carlos Aguilar Mares
Carlos Aguilar Mares

Reputation: 13601

There is no built-in way to allow that, but I think you should be able to write a quick module that provides the "IP Authentication" and that would allow you to have that in addition to other authentication modules and whichever provides an Identity will work.

For example, here is a quick sample:

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

then in your web.config configure the module as well as the ipAddresses allowed, for example:

  <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>

This will allow access to 127.0.0.1, and inject a "IPAddressRole" role in the identity, so you could even provide access above, and restrict/allow different access levels based on that role which represents the IP. It also will use the user name as the ip address so in the logs et all you will see that.

Upvotes: 2

Related Questions