前言
本篇展示了如何在ASP.NET Core應用程式中設定IP白名單驗證的2種方式,
你可以使用以下2種方式:
-
用于檢查每個請求的遠程 IP 地址的中間件,
-
MVC 操作篩選器,用于檢查針對特定控制器或操作方法的請求的遠程 IP 地址,
中間件
Startup.Configure方法將自定義 AdminSafeListMiddleware 中間件型別添加到應用的請求管道, 使用 .NET Core 配置提供程式檢索到該安全,并將其作為建構式引數進行傳遞,
app.UseMiddleware<AdminSafeListMiddleware>("127.0.0.1;192.168.1.5;::1");
中間件將字串分析為陣列,并在陣列中搜索遠程 IP 地址, 如果找不到遠程 IP 地址,中間件將回傳 HTTP 403 禁止訪問, 對于 HTTP GET 請求,將跳過此驗證程序,
public class AdminSafeListMiddleware{private readonly RequestDelegate _next;private readonly ILogger<AdminSafeListMiddleware> _logger;private readonly string _safelist;public AdminSafeListMiddleware(RequestDelegate next,ILogger<AdminSafeListMiddleware> logger,string safelist){_safelist = safelist;_next = next;_logger = logger;}public async Task Invoke(HttpContext context){if (context.Request.Method != HttpMethod.Get.Method){var remoteIp = context.Connection.RemoteIpAddress;_logger.LogDebug("Request from Remote IP address: {RemoteIp}", remoteIp);string[] ip = _safelist.Split(';');var bytes = remoteIp.GetAddressBytes();var badIp = true;foreach (var address in ip){var testIp = IPAddress.Parse(address);if (testIp.GetAddressBytes().SequenceEqual(bytes)){badIp = false;break;}}if (badIp){_logger.LogWarning("Forbidden Request from Remote IP address: {RemoteIp}", remoteIp);context.Response.StatusCode = StatusCodes.Status403Forbidden;return;}}await _next.Invoke(context);}}
操作篩選器
如果需要針對特定 MVC 控制器或操作方法的安全安全訪問控制,請使用操作篩選器, 例如:,
public class ClientIpCheckActionFilter : ActionFilterAttribute{private readonly ILogger _logger;private readonly string _safelist;public ClientIpCheckActionFilter(string safelist, ILogger logger){_safelist = safelist;_logger = logger;}public override void OnActionExecuting(ActionExecutingContext context){var remoteIp = context.HttpContext.Connection.RemoteIpAddress;_logger.LogDebug("Remote IpAddress: {RemoteIp}", remoteIp);var ip = _safelist.Split(';');var badIp = true;if (remoteIp.IsIPv4MappedToIPv6){remoteIp = remoteIp.MapToIPv4();}foreach (var address in ip){var testIp = IPAddress.Parse(address);if (testIp.Equals(remoteIp)){badIp = false;break;}}if (badIp){_logger.LogWarning("Forbidden Request from IP: {RemoteIp}", remoteIp);context.Result = new StatusCodeResult(StatusCodes.Status403Forbidden);return;}base.OnActionExecuting(context);}}
在中 Startup.ConfigureServices ,將操作篩選器添加到 MVC 篩選器集合, 在下面的示例中, ClientIpCheckActionFilter 添加了一個操作篩選器, 安全日志和控制臺記錄器實體作為建構式引數進行傳遞,
services.AddScoped<ClientIpCheckActionFilter>(container =>{var loggerFactory = container.GetRequiredService<ILoggerFactory>();var logger = loggerFactory.CreateLogger<ClientIpCheckActionFilter>();return new ClientIpCheckActionFilter("127.0.0.1;192.168.1.5;::1", logger);});
然后,可以將操作篩選器應用到具有 [ServiceFilter] 屬性的控制器或操作方法:
[ServiceFilter(typeof(ClientIpCheckActionFilter))][HttpGet]public IEnumerable<string> Get()
在示例應用中,操作篩選器將應用于控制器的 Get 操作方法, 當你通過發送來測驗應用程式時:
-
HTTP GET 請求,該
[ServiceFilter]屬性驗證客戶端 IP 地址, 如果允許訪問Get操作方法,則 "操作篩選器" 和 "操作" 方法將生成以下控制臺輸出的變體:
dbug: ClientIpSafelistComponents.Filters.ClientIpCheckActionFilter[0]Remote IpAddress: ::1dbug: ClientIpAspNetCore.Controllers.ValuesController[0]successful HTTP GET
除 GET 之外的 HTTP 請求謂詞將 AdminSafeListMiddleware 驗證客戶端 IP 地址,
總結
該案例完全可以改造成黑名單攔截,
關注公眾號:UP技術控 獲取更多資訊
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/225510.html
標籤:.NET技术
