Skip to content

Instantly share code, notes, and snippets.

@kevinhillinger
Created March 2, 2017 16:40
Show Gist options
  • Save kevinhillinger/d0e5d25f8c00037a5e03b0e3021d7fdf to your computer and use it in GitHub Desktop.
Save kevinhillinger/d0e5d25f8c00037a5e03b0e3021d7fdf to your computer and use it in GitHub Desktop.
Setting IP Restrictions on web.config through a data source
using IpRestrict.App_Start;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
namespace IpRestrict
{
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
IpSecurityConfig.RegisterIpRestrictions();
}
}
}
using Microsoft.Web.Administration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
// Install-Package Microsoft.Web.Administration
namespace IpRestrict.App_Start
{
public class IpSecurity
{
public string IpAddress { get; set; }
public bool Allowed { get; set; }
public string SubnetMask { get; set; }
}
public static class ConfigurationElementCollectionExtensions
{
public static ConfigurationElement AsConfigurationElement(this ConfigurationElementCollection collection, IpSecurity ipSecurity)
{
var element = collection.CreateElement("add");
element["ipAddress"] = ipSecurity.IpAddress;
element["allowed"] = ipSecurity.Allowed;
if (!string.IsNullOrEmpty(ipSecurity.SubnetMask))
{
element["subnetMask"] = ipSecurity.SubnetMask;
}
return element;
}
}
public class IpSecurityConfig
{
internal static void RegisterIpRestrictions()
{
using (ServerManager serverManager = new ServerManager())
{
var config = serverManager.GetApplicationHostConfiguration();
var ipSecuritySection = config.GetSection("system.webServer/security/ipSecurity");
var ipSecurityCollection = ipSecuritySection.GetCollection();
var ipSecurity = GetIpSecurity();
ipSecurity
.Select(ip => ipSecurityCollection.AsConfigurationElement(ip))
.ToList()
.ForEach(e => ipSecurityCollection.Add(e));
serverManager.CommitChanges();
}
}
static IEnumerable<IpSecurity> GetIpSecurity()
{
//return from table source, file, etc. instead of hard-coded
return new List<IpSecurity>()
{
new IpSecurity { Allowed = false, IpAddress = @"192.168.100.1" },
new IpSecurity { Allowed = false, IpAddress = @"169.254.0.0", SubnetMask = @"255.255.0.0" }
};
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment