简体   繁体   English

如何仅允许一组IP使用ASP.NET从后面的代码访问站点?

[英]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. 我将在header.aspx文件中使用这部分代码。

I'm assuming you are hosting this with IIS? 我假设您是使用IIS托管的吗?

in IIS 6 在IIS 6中

Right click on the website, and Under 'Directory Security' You can Grant / Deny the ip addresses range you wish. 右键单击该网站,然后在“目录安全性”下可以授予/拒绝所需的IP地址范围。

Well, the easiest way would be not to use code at all, but to implement the IP address restrictions in IIS, as darwindave suggests. 好吧,最简单的方法是根本不使用代码,而是按照darwindave的建议在IIS中实现IP地址限制。

But if you want to code it: Request.UserHostAddress contains the IP address the request is coming from. 但是,如果要对其进行编码: Request.UserHostAddress包含请求来自的IP地址。 Compare this to the IP-address or addresses you want to allow, and Response.Redirect to an error page if it doesn't match. 将此与您要允许的一个或多个IP地址进行比较,然后将Response.Redirect到错误页面(如果不匹配)。

Use an IP-blocker http module, don't ever do such a thing in the codebehind. 使用IP阻止程序http模块,永远不要在后面的代码中这样做。 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. 当然,除了禁止在web.config中列出的列表之外,您还需要禁止所有不以192.168或10开头的内容或内部使用的任何内容。

VB.NET : 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# : 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: PS:您可以将模块放入asp.net解决方案中,然后无需添加web.config条目:

Add it in global.asax : 将其添加到global.asax中

VB.NET 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# 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);
}

我可以通过IPSec进行操作,右键单击NIC上的“高级”,然后查找名为IpSec的内容。您可以在其中筛选NIC,使其仅与某些IP地址对话。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我如何使用反射从文件后面的asp.net代码访问服务器端控件? - How can i access a server side control from asp.net code behind file using reflection? 如何访问文本框,使用asp.net Web表单从代码后面的更新面板内标签 - How to access textbox, label inside update panel from code behind using asp.net web forms c#从asp.net页面访问背后的代码 - c# Code behind access from asp.net page 如何从asp.net中的模式对话框访问click事件代码背后的代码 - How to access the code behind click event code from a modal dialog box in asp.net 如何从 ASP 中的代码访问站点母版页控件? - How to access site master page controls from code behind in ASP? 使用ASP.NET C#从背后的代码访问数据库数据 - Access database data from the code behind using ASP.NET C# ASP.NET身份-如何仅允许访问已登录的用户? - ASP.NET Identity - How to allow access to ONLY the logged in User? 如何从DNN皮肤代码后面访问asp.net控件 - How to access asp.net controls from DNN skin code behind asp.net:如何访问从后面的代码创建的表的单元格内的文本框的内容 - asp.net: how to access contents of a textbox inside the cell of a table that was created from the code behind 在ASP.NET中使用jquery从后面的代码中将文本框清除为0 - Clear textboxes to 0 in ASP.NET using jquery from code behind
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM