Asp.Net Core 中如何设置 IP 白名单

咨询区

  • MartinM

我想在一个web站点中实现ip白名单功能,在 MVC 时代我只需要在 web.config 中添加如下配置即可。


<security>
  <ipSecurity allowUnlisted="false" denyAction="NotFound">
    <add allowed="true" ipAddress="XX.XX.XX.XX" subnetMask="255.255.255.0"/>
  </ipSecurity>
</security>

但在 AspNetCore 中使用如上配置时,程序启动就会报错。


Unable to start process The web server request failed with status code 500, internal server error

很显然这个 config 配置是有问题的,请问是否有内置或者第三方的组件来实现这个功能?

回答区

  • Ergwun

Damian Bod 写了一篇文章:https://damienbod.com/2016/12/18/implementing-a-client-white-list-using-asp-net-core-middleware/ 来演示如果通过中间件的方式来实现 ip 白名单功能。

他分别给了一个 全局性中间件actionfilter 两种方式来实现,无论哪种方式都需要在 appsetttings.json 中配置可允许访问的 ip 列表,然后根据这个list来检查客户端的ip是否符合?client ip 可以通过 context.Connection.RemoteIpAddress 来获取。

如果你有更精细化的配置,比如说设置ip段,那你可以通过nuget上的 IPAddressRange 包来实现,它支持了多种格式,如:192.168.0.0/24192.168.0.0/255.255.255.0,包括 CIDR 表达式和 IPv6。

参考下面的例子。

  1. 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
    ]
  }
}

  1. IPWhiteListConfiguration.cs:


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

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

  1. IIPWhiteListConfiguration.cs:


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

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

  1. 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);
        // ...
    }
 }

  1. 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();
            }
        }
    }
}

点评区

在 website 中设置ip白名单的功能非常常见,nuget上也有很多的开源中间件帮助实现,比如:ClientIpAspNetCoreIIS,我在项目中也有用到白名单的功能,只不过是做到了 nginx 层。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
设置白名单访问API,可以使用ASP.NET Core中间件来实现。以下是设置白名单的步骤: 1. 创建一个中间件类,例如名为WhitelistMiddleware的类。 2. 在WhitelistMiddleware实现Invoke方法,检查请求IP地址是否在白名单。如果是,则继续执行管道的下一个中间件,否则返回403 Forbidden响应。 3. 在Startup类添加中间件,将WhitelistMiddleware添加到管道,并将白名单IP地址作为参数传递给中间件。 以下是一个示例WhitelistMiddleware类的代码: ```csharp using Microsoft.AspNetCore.Http; using System.Net; using System.Threading.Tasks; public class WhitelistMiddleware { private readonly RequestDelegate _next; private readonly string[] _allowedIPs; public WhitelistMiddleware(RequestDelegate next, string[] allowedIPs) { _next = next; _allowedIPs = allowedIPs; } public async Task Invoke(HttpContext context) { var ipAddress = context.Connection.RemoteIpAddress; if (_allowedIPs.Contains(ipAddress.ToString())) { await _next.Invoke(context); } else { context.Response.StatusCode = (int)HttpStatusCode.Forbidden; } } } ``` 在Startup类,可以使用以下代码将中间件添加到管道: ```csharp public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { // ... app.UseMiddleware<WhitelistMiddleware>(new[] { "127.0.0.1", "::1" }); // ... } ``` 在这个例子,我们将添加一个名为WhitelistMiddleware中间件,并将IP地址为127.0.0.1和::1的地址添加到白名单。这意味着只有来自本地计算机的请求才能访问API。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值