RoundOutTooSoon
RoundOutTooSoon

Reputation: 9891

How to allow only a group of IPs access the site from code behind using ASP.NET?

I have this website where I want just only the computers in our office have access to it. How can I write code to do this? I've been looking all over the web but I couldn't find anything like this.

Sorry I couldn't write any code about this before posting this question.

I will be using this part of code in the header.aspx file.

Upvotes: 0

Views: 2839

Answers (4)

Stefan Steiger
Stefan Steiger

Reputation: 82396

Use an IP-blocker http module, don't ever do such a thing in the codebehind. Of course, instead of banning a list listed in web.config, you need to ban anything that doesn't start with 192.168 or 10. or whatever you use internally.

VB.NET:

Imports System.Web

' http://support.microsoft.com/kb/308000
' http://www.c-sharpcorner.com/UploadFile/hemantkathuria/ASPNetHttpModules11262005004251AM/ASPNetHttpModules.aspx
' http://www.15seconds.com/issue/020417.htm
' http://www.worldofasp.net/tut/prjaspxmod/ASPNET_HTTP_Modules_168.aspx
' http://dotnetslackers.com/articles/aspnet/ErrorLoggingModulesAndHandlers.aspx
' http://www.stardeveloper.com/articles/display.html?article=2009071801&page=1
' http://www.devx.com/dotnet/Article/6962/1954
' http://www.west-wind.com/weblog/posts/59731.aspx


Public Class IPbanning
    Implements IHttpModule

    Private Shared m_scIPadresses As System.Collections.Specialized.StringCollection = FillBlockedIps()

    Public Sub Dispose() Implements System.Web.IHttpModule.Dispose
    End Sub

    Public Sub Init(ByVal context As System.Web.HttpApplication) Implements System.Web.IHttpModule.Init
        AddHandler context.BeginRequest, New EventHandler(AddressOf context_BeginRequest)
        'AddHandler context.EndRequest, New EventHandler(AddressOf IHttpModule_Dispose)
    End Sub

    ''' <summary>
    ''' Checks the requesting IP address in the collection
    ''' and block the response if it's on the list.
    ''' </summary>
    Private Sub context_BeginRequest(ByVal sender As Object, ByVal e As EventArgs)

        Dim strIP As String = HttpContext.Current.Request.UserHostAddress

        If String.IsNullOrEmpty(strIP) Then
            HttpContext.Current.Response.Write("<h1>Server-Error: IP is NULL</h1>")
            HttpContext.Current.Response.End()
            Exit Sub
        End If

        If strIP = "127.0.0.2" Then
            HttpContext.Current.Response.Write("<h1 style=""color: blue;""><font color=""red"">YOU</font> (" + HttpContext.Current.Request.UserHostAddress.ToString() + ") are banned.</h1>")
            'HttpContext.Current.Response.StatusCode = 403
            HttpContext.Current.Response.End()
        End If

        If (m_scIPadresses.Contains(strIP)) Then
            HttpContext.Current.Response.StatusCode = 403
            HttpContext.Current.Response.End()
        End If
    End Sub

    ''' <summary>
    ''' Retrieves the IP addresses from the web.config
    ''' and adds them to a StringCollection.
    ''' </summary>
    ''' <returns>A StringCollection of IP addresses.</returns>
    Private Shared Function FillBlockedIps() As System.Collections.Specialized.StringCollection

        Dim scIPcollection As System.Collections.Specialized.StringCollection = New System.Collections.Specialized.StringCollection()
        'Dim strRaw As String = ConfigurationManager.AppSettings.Get("blockip")
        Dim strRaw As String = "44.0.234.122, 23.4.9.231"
        strRaw = strRaw.Replace(",", ";")
        strRaw = strRaw.Replace(" ", ";")

        For Each strIP As String In strRaw.Split(";")
            scIPcollection.Add(strIP.Trim())
        Next

        Return scIPcollection
    End Function
End Class

C#:

using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Web;

// http://support.microsoft.com/kb/308000
// http://www.c-sharpcorner.com/UploadFile/hemantkathuria/ASPNetHttpModules11262005004251AM/ASPNetHttpModules.aspx
// http://www.15seconds.com/issue/020417.htm
// http://www.worldofasp.net/tut/prjaspxmod/ASPNET_HTTP_Modules_168.aspx
// http://dotnetslackers.com/articles/aspnet/ErrorLoggingModulesAndHandlers.aspx
// http://www.stardeveloper.com/articles/display.html?article=2009071801&page=1
// http://www.devx.com/dotnet/Article/6962/1954
// http://www.west-wind.com/weblog/posts/59731.aspx

public class IPbanning : IHttpModule
{

    private static System.Collections.Specialized.StringCollection m_scIPadresses = FillBlockedIps();

    public void Dispose()
    {
    }

    public void Init(System.Web.HttpApplication context)
    {
        context.BeginRequest += new EventHandler(context_BeginRequest);
        //AddHandler context.EndRequest, New EventHandler(AddressOf IHttpModule_Dispose)
    }

    /// <summary>
    /// Checks the requesting IP address in the collection
    /// and block the response if it's on the list.
    /// </summary>

    private void context_BeginRequest(object sender, EventArgs e)
    {
        string strIP = HttpContext.Current.Request.UserHostAddress;

        if (string.IsNullOrEmpty(strIP)) {
            HttpContext.Current.Response.Write("<h1>Server-Error: IP is NULL</h1>");
            HttpContext.Current.Response.End();
            return;
        }

        if (strIP == "127.0.0.2") {
            HttpContext.Current.Response.Write("<h1 style=\"color: blue;\"><font color=\"red\">YOU</font> (" + HttpContext.Current.Request.UserHostAddress.ToString() + ") are banned.</h1>");
            //HttpContext.Current.Response.StatusCode = 403
            HttpContext.Current.Response.End();
        }

        if ((m_scIPadresses.Contains(strIP))) {
            HttpContext.Current.Response.StatusCode = 403;
            HttpContext.Current.Response.End();
        }
    }

    /// <summary>
    /// Retrieves the IP addresses from the web.config
    /// and adds them to a StringCollection.
    /// </summary>
    /// <returns>A StringCollection of IP addresses.</returns>
    private static System.Collections.Specialized.StringCollection FillBlockedIps()
    {
        System.Collections.Specialized.StringCollection scIPcollection = new System.Collections.Specialized.StringCollection();
        //Dim strRaw As String = ConfigurationManager.AppSettings.Get("blockip")
        string strRaw = "44.0.234.122, 23.4.9.231";
        strRaw = strRaw.Replace(",", ";");
        strRaw = strRaw.Replace(" ", ";");

        foreach (string strIP in strRaw.Split(";")) {
            scIPcollection.Add(strIP.Trim());
        }

        return scIPcollection;
    }
}

PS: You can put the module into the asp.net solution, then you don't need to add a web.config entry:

Add it in global.asax:

VB.NET

Public Shared ThatModule As IHttpModule = New WebServiceAuthenticationModule()

' http://www.west-wind.com/weblog/posts/44979.aspx
Public Overrides Sub Init()
    MyBase.Init()
    ThatModule.Init(Me)
End Sub

C#

public static IHttpModule ThatModule = new WebServiceAuthenticationModule();
// http://www.west-wind.com/weblog/posts/44979.aspx
public override void Init()
{
    base.Init();
    ThatModule.Init(this);
}

Upvotes: 2

Carson63000
Carson63000

Reputation: 4232

Well, the easiest way would be not to use code at all, but to implement the IP address restrictions in IIS, as darwindave suggests.

But if you want to code it: Request.UserHostAddress contains the IP address the request is coming from. Compare this to the IP-address or addresses you want to allow, and Response.Redirect to an error page if it doesn't match.

Upvotes: 2

Aaron Kempf
Aaron Kempf

Reputation: 588

I could do it via IPSec, right-click advanced on the NIC, and look for something called IpSec.. there you can filter the NIC to only talk to certain IP Addresses.

Upvotes: 0

tourdownunder
tourdownunder

Reputation: 1839

I'm assuming you are hosting this with IIS?

in IIS 6

Right click on the website, and Under 'Directory Security' You can Grant / Deny the ip addresses range you wish.

Upvotes: 2

Related Questions