Best way to check IP address in a lot of pages

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

Andrew Banks

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

Nick

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

Munsifali Rashid

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top