Asp.Net Core安全防禦-客戶端IP白名單限制

前言

本篇展現瞭如何在ASP.NET Core應用程序中設置IP白名單驗證的2種方式。javascript

你能夠使用如下2種方式:php

  • 用於檢查每一個請求的遠程 IP 地址的中間件。css

  • MVC 操做篩選器,用於檢查針對特定控制器或操做方法的請求的遠程 IP 地址。java

 

中間件

Startup.Configure方法將自定義 AdminSafeListMiddleware 中間件類型添加到應用的請求管道。 使用 .NET Core 配置提供程序檢索到該安全,並將其做爲構造函數參數進行傳遞。typescript

 

 

app.UseMiddleware<AdminSafeListMiddleware>("127.0.0.1;192.168.1.5;::1");

中間件將字符串分析爲數組,並在數組中搜索遠程 IP 地址。 若是找不到遠程 IP 地址,中間件將返回 HTTP 403 禁止訪問。 對於 HTTP GET 請求,將跳過此驗證過程。apache






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 控制器或操做方法的安全安全訪問控制,請使用操做篩選器。 例如:。json







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 操做方法。 當你經過發送來測試應用程序時:ruby

  • 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技術控   獲取更多資訊

相關文章
相關標籤/搜索