| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455 |
- using System.Net;
- namespace DopInterfacePlatform
- {
- public class IpWhiteListMiddleware
- {
- private readonly RequestDelegate _next;
- private readonly ILogger<IpWhiteListMiddleware> _logger;
- private readonly string _adminSafeList;
- public IpWhiteListMiddleware(
- RequestDelegate next,
- ILogger<IpWhiteListMiddleware> logger,
- string adminSafeList)
- {
- _adminSafeList = adminSafeList;
- _next = next;
- _logger = logger;
- }
- public async Task Invoke(HttpContext context)
- {
- if (context.Request.Method != "GET")
- {
- var remoteIp = context.Connection.RemoteIpAddress;
- _logger.LogDebug($"Request from Remote IP address: {remoteIp}");
- string[] ip = _adminSafeList.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.LogInformation(
- $"Forbidden Request from Remote IP address: {remoteIp}");
- context.Response.StatusCode = (int)HttpStatusCode.Forbidden;
- return;
- }
- }
- await _next.Invoke(context);
- }
- }
- }
|