且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Asp.Net Core 中的 IP 安全性

更新时间:2023-08-31 17:56:16

Damian Bod 做了一个 博文 演示如何实现中间件来处理 IP 白名单.

Damian Bod has made a blog post demonstrating how to implement middleware to handle IP whitelisting.

他给出了全局中间件或动作过滤器的例子.

He gives examples of global middleware or action filter.

无论哪种方式,您都需要将允许的 IP 地址添加到您的 appsettings.json 中,并对照它们检查客户端 IP 地址.

Either way you need to add permitted IP addresses to your appsettings.json, and check the client IP address against them.

客户端 IP 地址可通过 HttpContext 获得(例如 context.Connection.RemoteIpAddress).

Client IP address is available via HttpContext (e.g. context.Connection.RemoteIpAddress).

如果你想将 IP 地址范围列入白名单,那么你可以使用 Nuget 包 IPAddressRange,它支持各种格式,例如192.168.0.0/24"和192.168.0.0/255.255.255.0",包括 CIDR 表达式和 IPv6.

If you want to whitelist IP address ranges, then you can use the Nuget package IPAddressRange, which supports various formats such as "192.168.0.0/24" and "192.168.0.0/255.255.255.0", including CIDR expressions and IPv6.

这是一个如何在过滤器中执行此操作的示例:

Here's an example of how to do that in a filter:

appsettings.json:

{
  "IPAddressWhitelistConfiguration": {
    "AuthorizedIPAddresses": [
      "::1", // IPv6 localhost
      "127.0.0.1", // IPv4 localhost
      "192.168.0.0/16", // Local network
      "10.0.0.0/16", // Local network
    ]
  }
}

IPWhiteListConfiguration.cs:

namespace My.Web.Configuration
{
    using System.Collections.Generic;

    public class IPWhitelistConfiguration : IIPWhitelistConfiguration
    {
        public IEnumerable<string> AuthorizedIPAddresses { get; set; }
    }
}

IIPWhiteListConfiguration.cs:

namespace My.Web.Configuration
{
    using System.Collections.Generic;

    public interface IIPWhitelistConfiguration
    {
        IEnumerable<string> AuthorizedIPAddresses { get; }
    }
}

Startup.cs:

public class Startup
{
    // ...
    public void ConfigureServices(IServiceCollection services)
    {
        // ...
        services.Configure<IPWhitelistConfiguration>(
           this.Configuration.GetSection("IPAddressWhitelistConfiguration"));
        services.AddSingleton<IIPWhitelistConfiguration>(
            resolver => resolver.GetRequiredService<IOptions<IPWhitelistConfiguration>>().Value);
        // ...
    }
 }

ClientIPAddressFilterAttribute.cs:

namespace My.Web.Filters
{
    using System.Collections.Generic;
    using System.Linq;
    using System.Net;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.AspNetCore.Mvc.Filters;
    using NetTools;
    using My.Web.Configuration;

    public class ClientIPAddressFilterAttribute : ActionFilterAttribute
    {
        private readonly IEnumerable<IPAddressRange> authorizedRanges;

        public ClientIPAddressFilterAttribute(IIPWhitelistConfiguration configuration)
        {
            this.authorizedRanges = configuration.AuthorizedIPAddresses
                .Select(item => IPAddressRange.Parse(item));
        }

        public override void OnActionExecuting(ActionExecutingContext context)
        {
            var clientIPAddress = context.HttpContext.Connection.RemoteIpAddress;
            if (!this.authorizedRanges.Any(range => range.Contains(clientIPAddress)))
            {
                context.Result = new UnauthorizedResult();
            }
        }
    }