2024年2月5日发(作者:)

Core中客户端IP白名单限制

1.使用中间件来限制客户端 IP:

public class IpWhitelistMiddleware

{

private readonly RequestDelegate _next;

private readonly string[] _allowedIps;

public IpWhitelistMiddleware(RequestDelegate next, string[] allowedIps)

{

_next = next;

_allowedIps = allowedIps;

}

public async Task InvokeAsync(HttpContext context)

{

var clientIp = ng();

if (!_ns(clientIp))

{ Code = 403Forbidden;

await = new StatusCodeResult(401);

// await sync("Access denied.");

return;

}

await _next(context);

}

}

在上面的示例中,我们创建了一个名为 IpWhitelistMiddleware 的中间件类。构造函数中注入了 RequestDelegate 和允许的 IP 地址列表。InvokeAsync 方法中,我们获取客户端的 IP

地址,并检查它是否在允许的 IP 地址列表中。如果不在列表中,我们设置响应状态码为 403(禁止访问)并返回。否则,我们继续处理请求。

要在 Core 应用中使用这个中间件,您需要在 文件的 Configure 方法中进行注册:

public void Configure(IApplicationBuilder app)

{

//从配置文件读取

dleware(

Configuration["AdminSafeList"]);

//var allowedIps = new[] { "192.168.0.1", "10.0.0.1" }; // 允许的 IP 地址列表

// dleware(allowedIps);

// ... 其他中间件注册 ...

ting();

points(endpoints =>

{

trollers();

});

}

在上面的示例中,我们在中间件注册时传递了允许的 IP 地址列表。这样,当有请求到达

Core 应用时,中间件将检查客户端的 IP 地址是否在白名单中。如果不在,将返回

403 禁止访问的响应。

2.使用Action过滤器

如果你只是希望为某些特性的Controller或Action方法添加IP白名单,你可以使用Action过滤器。

这里我们首先添加一个新类ClientIdCheckFilter, 它继承自ActionFilterAttribute

public class ClientIdCheckFilter : ActionFilterAttribute

{

private readonly string _safelist;

public ClientIdCheckFilter

(IConfiguration configuration)

{

_safelist = configuration["AdminSafeList"];

}

public override void OnActionExecuting(ActionExecutingContext context)

{

var remoteIp = IpAddress;

if (!_safelist .Contains(clientIp))

{

Code = 403Forbidden;

await = new StatusCodeResult(401);

return;

}

onExecuting(context);

}

}

这里我们复写了OnActionExecuting方法,如果当前客户端 IP存在于白名单中,我们就调用基类OnActionExecuting方法,执行当前Action请求,否则就返回一个401状态码

这里没有针对请求类型的判断,所以指定当前过滤器的Action,GET请求也会受到白名单的

限制

第二步,我们需要将这action过滤器添加到服务容器中。

public void ConfigureServices(IServiceCollection services)

{

ped();

(options =>

{

(new ClientIdCheckPageFilter

(_loggerFactory, Configuration));

}).SetCompatibilityVersion(n_2_1);

}

第三步,我们可以在Action方法声明处添加ServiceFilter特性,传入的参数是我们之前定义好的ClientIdCheckFilter。

例:

[ServiceFilter(typeof(ClientIdCheckFilter))]

[HttpGet]

public IEnumerable Get()

3.使用IPageFilter

Razor Pages应用是 Core 2.0中新引入的功能,它是 Core Mvc的一个子集。

如果希望Razor Pages应用支持IP白名单,我们需要创建一个新类ClientIdCheckPageFilter, 它实现了IPageFilter接口.

public class ClientIdCheckPageFilter : IPageFilter

{

private readonly ILogger _logger;

private readonly string _safelist;

public ClientIdCheckPageFilter

(ILoggerFactory loggerFactory, IConfiguration configuration)

{

_logger = Logger("ClientIdCheckPageFilter");

_safelist = configuration["AdminSafeList"];

}

public void OnPageHandlerExecuting(PageHandlerExecutingContext context)

{

_ormation(

$"Remote IpAddress: {IpAddress}");

var remoteIp = IpAddress;

_ug($"Request from Remote IP address: {remoteIp}");

string[] ip = _(';');

var bytes = ressBytes();

var badIp = true;

foreach (var address in ip)

{

var testIp = (address);

if (ressBytes().SequenceEqual(bytes))

{

badIp = false;

break;

}

}

if (badIp)

{

_ormation(

$"Forbidden Request from Remote IP address: {remoteIp}");

= new StatusCodeResult(401);

return;

}

}

public void OnPageHandlerExecuted(PageHandlerExecutedContext context)

{

}

public void OnPageHandlerSelected(PageHandlerSelectedContext context)

{

}

}

这里的代码实现和IActionFilter的实现基本一样,唯一的区别是代码放在了OnPageHandlerExecuting的实现中。

第二步,我们还是需要将ClientIdCheckPageFilter添加到MVC的过滤器集合中。

public void ConfigureServices(IServiceCollection services)

{

ped();

(options =>

{

(new ClientIdCheckPageFilter

(_loggerFactory, Configuration));

}).SetCompatibilityVersion(n_2_1);

}