namespace LisansNetCoreApi.Helper { public class SwaggerIpRestrictionMiddleware { private readonly RequestDelegate _next; private readonly IConfiguration _configuration; public SwaggerIpRestrictionMiddleware(RequestDelegate next, IConfiguration configuration) { _next = next; _configuration = configuration; } public async Task Invoke(HttpContext context) { var requestPath = context.Request.Path; // Sadece /swagger yolu için kontrol yap if (requestPath.StartsWithSegments("/swagger")) { // Güncel IP listesini her istekte oku var allowedIps = _configuration.GetSection("AllowedIps").Get<List<string>>() ?? new List<string>(); var remoteIp = context.Connection.RemoteIpAddress?.ToString(); // İstemci IP'si izin verilen IP listesinde değilse erişimi engelle if (!allowedIps.Contains(remoteIp)) { context.Response.StatusCode = StatusCodes.Status403Forbidden; context.Response.ContentType = "text/plain; charset=utf-8"; // UTF-8 desteği await context.Response.WriteAsync($"{remoteIp} Swagger erişimi yalnızca belirli IP adresleri için açıktır."); return; } } await _next(context); } } } |