.Net Core API IP Kısıtlama | C#

Merhaba, .net Core ile yazdığım bir API’de sadece belirli IP adreslerinden gelen istekler işlensin istedim.

Şu şekilde yapıldığını öğrendim ve uyguladım, çalıştı.

public interface IIpBlockingService
{
	bool IsAllowed(IPAddress ipAddress);
}

public class IpBlockingService : IIpBlockingService
{
	private readonly List<string> _allowedIps;
	public IpBlockingService(IConfiguration configuration)
	{
		_allowedIps = configuration.GetValue<string>("ApplicationOptions:Whitelist").Split(';').ToList();
	}
	public bool IsAllowed(IPAddress ipAddress) => _allowedIps.Contains(ipAddress.ToString());
}

public class IpBlockMiddleware
{
	private readonly RequestDelegate _next;
	private readonly IIpBlockingService _blockingService;
	public IpBlockMiddleware(RequestDelegate next, IIpBlockingService blockingService)
	{
		_next = next;
		_blockingService = blockingService;
	}
	public async Task Invoke(HttpContext context)
	{
		IPAddress remoteIp = context.Connection.RemoteIpAddress;
		bool isAllowed = _blockingService.IsAllowed(remoteIp!);
		if (!isAllowed)
		{
			context.Response.StatusCode = (int)HttpStatusCode.Forbidden;
			return;
		}
		await _next.Invoke(context);
	}
}

Program.cs içine şunları eklemeliyiz:


....
builder.Services.AddTransient<IIpBlockingService, IpBlockingService>();
...
...
app.UseMiddleware<IpBlockMiddleware>();
.....

appsettings.json dosyası da şu şekilde olabilir:

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "ApplicationOptions": {
    "Whitelist": "111.111.111.111;222.222.222.222" 
  },
  "AmazonBaglanti": {
    "RefreshToken": "ccc"
  }
}

Selamlar.

Leave a Reply

Your email address will not be published. Required fields are marked *