How to allow/ deny IP access to a specific IP address through web.config

Programming, error messages and sample code > sample code
If you need to restricts some IP address to accessing your website or application then you have to add the code in your web.config file and put that file in to the particular directory which you wish to protect from access. As you know about web.config file that is it in XML format and you have to add <security> tag to allow or deny particular IP address. In this article we are going to explain how to block Ip address via web.config file for your ASP.net application. Let’s see....
 
How to block single IP or multiple IP addresses?

You can block desired IP address or blocks a range of IP address it’s totally depend on you. If you need to give access to your website for just single IP then this code is very useful for you. Through this no one can access your website except you.

Code to block specific IP address and Allow all IP:

With the below code IP address (xxx.xxx.xxx.xxx) is blocked.
 
<security>
<ipSecurity allowUnlisted="true">  <!-- line allows everyone, except  below IP-->
<clear/>
<add ipAddress="127.0.0.1" allowed="true"/>
<add ipAddress="xxx.xxx.xxx.xxx"/>  <!-- blocks the specific IP -->
<add ipAddress="xxx.xxx.xxx.0" subnetMask="255.255.255.0"/>  <!--blocks network xxx.xxx.xxx.0 to xxx.xxx.xxx.255-->
</ipSecurity>
</security>
Code to deny all and allow specific IP address:

This code can blocks all the IP addresses and allow only single IP. Here IP is xxx.xxx.xxx.xxx
<security>
<ipSecurity allowUnlisted="false">  <!-- line blocks everyone, except  below IP -->
<clear/>
<add ipAddress="127.0.0.1" allowed="true"/>
<add ipAddress="xxx.xxx.xxx.xxx" allowed="true"/>  <!-- allow the specific IP of xxx.xxx.xxx.xxx  -->
<add ipAddress="xxx.xxx.xxx.0" subnetMask="255.255.255.0" allowed="true"/>  <!--allow network xxx.xxx.xxx.0 to xxx.xxx.xxx.255-->
</ipSecurity>
</security>
NOTE: You can easily add the above code in your already created web.config file after <system.webServer> tag. You can also create a new web.config file in the particular directly which you want to protect.

To create a new web.config file in text editor you have to add the following code. As this file is a XML file then you have to start with xml tag. Your new web.config file looks like this.
<?xml version="1.0"?>
<configuration>
<system.web>
.. text ..
</system.web>
<system.webServer>
<security>
<ipSecurity allowUnlisted="true">  <!-- line blocks everyone, except  below IP -->
<clear/>
<add ipAddress="xxx.xxx.xxx.xxx"/>  <!-- blocks particular IP -->
<add ipAddress="xxx.xxx.xxx.0" subnetMask="255.255.255.0"/>  <!--block network xxx.xxx.xxx.0 to xxx.xxx.xxx.255-->
</ipSecurity>
</security>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
</configuration>