Many times we have sites that are public but have pages that should only be viewed by internal users.
Ideally the settings would be configured on the server level in IIS but if not possible for some reason this may help.
One key thing to note is this code will lock down access to a 10.x.x.x IP if you need to change that you need to add different options to the if (aIPAddress[0] != “10”) part of the code.
Example would be (aIPAddress[0] != “192” && aIPAddress[1] != “168”)
protected void Page_Load(object sender, EventArgs e)
{
string[] aIPAddress = GetIPAddress().Split('.');
if (aIPAddress[0] != "10")
{
Response.Write("Not Authorized");
Response.Redirect("https://example.com/");
}
else
{
// Response.Write("Authorized");
}
}
protected string GetIPAddress()
{
System.Web.HttpContext context = System.Web.HttpContext.Current;
string ipAddress = context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (!string.IsNullOrEmpty(ipAddress))
{
string[] addresses = ipAddress.Split(',');
if (addresses.Length != 0)
{
return addresses[0];
}
}
return context.Request.ServerVariables["REMOTE_ADDR"];
}
Originally Posted on September 26, 2013
Last Updated on October 26, 2015
Last Updated on October 26, 2015
All information on this site is shared with the intention to help. Before any source code or program is ran on a production (non-development) system it is suggested you test it and fully understand what it is doing not just what it appears it is doing. I accept no responsibility for any damage you may do with this code.