Best way to check IP address in a lot of pages

  • Thread starter Thread starter Andrew Banks
  • Start date Start date
A

Andrew Banks

I'm going to have an admin section to a site I'm developing using ASP.NET C#

I want to restrict access to this directory based on username and password
(I've got that bit done) but also upon the IP address of the user accessing
it. I only want my IP to get access to this directory but my IP may change
from time to time so this should be easy to change in the code - ideally in
one place.

Is this possible and if so what is the best way to do it?
 
That's what I was thinking. I've got my authorisation set to forms in their
and that's working fine for this directory, I just want to add the IP as an
extra measure.

Is this possibe anyone?
 
Well you've got the UserHostAddress in HttpRequest which gives the IP of the
client for the current Session. In the page that requires further
authentication, simply check this value with the list of allowable IPs,
possibly loaded from the web.config or elsewhere.
 
I don't think you can do this as a built in feature of asp.net. However,
you should be able to easily add the IP check into your forms authentication
code. Add a key to your web.config file with the IP Address:

<appSettings>
<add key="AdminIPAddress" value="a.b.c.d" />
</appSettings>

In the login check, check the remote IP Address against the allowed IP
Address:

string remoteIP = Request.ServerVariables["remote_addr"];
string allowedIP =
System.Configuration.ConfigurationSettings.AppSettings["AdminIPAddress"];

if (remoteIP == allowedIP)
{
bool isAuthenticated = FormsAuthentication.Authenticate(username,
password);
if (isAuthenticated)
{
// User logged in successfully and IP Address is valid
}
else
{
// User login failed, but IP Address is valid
}
}
else
{
// User login failed. IP Address is invalid
}

Hope this helps,

Mun
 
Back
Top