WebApi项目需要限制仅允许有限的客户端访问接口,百度相关内容,网上很多介绍WebApi接口IP限流的文章,稍微调整就能用于限制IP访问,微软官网中也有文章介绍客户端 IP 安全列表(参考文献1),可以通过中间件、过滤器等多种方式实现IP访问限制,本文学习和测试基于中间件实现WebApi接口限制客户端ip访问的基本用法。
基于中间件做IP限制,需要自定义中间件类,每次客户端访问前都会调用该中间件,从中间件中获取客户端访问IP并判断是否在指定的IP集合中,在的话允许访问接口,否则直接返回错误信息。
自定义中间件类的代码及其在program.cs文件中的使用方式如下所示:
// 自定义中间件类
public class IpFilterMiddleware
{
private readonly RequestDelegate _next;
private readonly string[] _allowedIps;
public IpFilterMiddleware(RequestDelegate next, IConfiguration config)
{
_next = next;
_allowedIps = config.GetSection("AllowedIps").Get<string>().Split(',');
}
public async Task Invoke(HttpContext context)
{
var clientIp = context.Connection.RemoteIpAddress?.ToString(); 址
if (_allowedIps.Contains(clientIp))
{
await _next(context);
}
else
{
context.Response.StatusCode = 403; // 返回403 Forbidden状态码
await context.Response.WriteAsync("客户端IP禁止访问WebApi接口");
}
}
}
//使用中间件类
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseMiddleware<IpFilterMiddleware>();//使用中间件类
app.UseWebSockets();
实现上面的代码后,客户端调用WebApi接口时即在IpFilterMiddleware中进行IP过滤,禁止访问的效果如下图所示:
参考文献:
[1]https://learn.microsoft.com/zh-cn/aspnet/core/security/ip-safelist?view=aspnetcore-9.0
[2]https://blog.csdn.net/sd7o95o/article/details/145102403