Skip to Content
Documentation백엔드 런타임ASP.NET Core (C#)

C#(ASP.NET 코어)

엔터프라이즈 Microsoft 환경의 경우 ProxyTracer를 ASP.NET Core HTTP 요청 파이프라인에 직접 통합하면 악성 트래픽이 라우팅, 모델 바인딩 또는 데이터베이스 쿼리를 트리거하기 전에 거부됩니다.

미들웨어

이 구현은 초고속 역직렬화를 위해 System.Text.Json을 사용하고 HttpClient를 통해 엄격한 시간 제한을 적용하며 플래그가 지정된 경우 403 Forbidden 응답으로 파이프라인을 단락시킵니다.

using System; using System.Net.Http; using System.Net.Http.Headers; using System.Text.Json; using System.Text.Json.Serialization; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; namespace ProxyTracer.Security { public class ProxyTracerMiddleware { private readonly RequestDelegate _next; private readonly HttpClient _httpClient; private readonly ILogger<ProxyTracerMiddleware> _logger; private readonly string _apiKey; public ProxyTracerMiddleware(RequestDelegate next, IConfiguration config, ILogger<ProxyTracerMiddleware> logger) { _next = next; _logger = logger; _apiKey = config["PROXYTRACER_API_KEY"] ?? throw new ArgumentNullException("PROXYTRACER_API_KEY is missing"); // 엄격한 500ms 타임아웃을 적용한 재사용 가능한 클라이언트 _httpClient = new HttpClient { Timeout = TimeSpan.FromMilliseconds(500) }; } public async Task InvokeAsync(HttpContext context) { // 1. IP 추출 (Program.cs에 app.UseForwardedHeaders() 구성 필요) var ip = context.Connection.RemoteIpAddress?.ToString(); // 로컬 개발 IP 건너뛰기 if (!string.IsNullOrEmpty(ip) && ip != "127.0.0.1" && ip != "::1") { try { // 2. ProxyTracer API 비동기 쿼리 using var request = new HttpRequestMessage(HttpMethod.Get, $"https://api.proxytracer.com/v1/check/{ip}"); request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _apiKey); using var response = await _httpClient.SendAsync(request); if (response.IsSuccessStatusCode) { using var jsonStream = await response.Content.ReadAsStreamAsync(); var ptResponse = await JsonSerializer.DeserializeAsync<ProxyTracerResult>(jsonStream); // 3. 프록시/VPN이 감지되면 연결 차단 if (ptResponse != null && ptResponse.Proxy) { context.Response.StatusCode = StatusCodes.Status403Forbidden; context.Response.ContentType = "application/json"; await context.Response.WriteAsync("{\"error\": \"Access Denied: VPN or Proxy detected.\"}"); return; // 요청 파이프라인 숏서킷(short-circuit) } } } catch (Exception ex) { // Fail open: 오류를 기록하고 요청 통과 허용 _logger.LogWarning($"ProxyTracer validation failed: {ex.Message}"); } } // 4. 정상 트래픽인 경우 컨트롤러로 전달 await _next(context); } // {"proxy": true|false} 응답에 정확히 매핑되는 경량 구조체 private class ProxyTracerResult { [JsonPropertyName("proxy")] public bool Proxy { get; set; } } } }

구성:

보호를 활성화하려면 'Program.cs' 파일에 미들웨어를 등록하세요. UseForwardedHeaders 뒤, UseRoutingUseAuthentication 앞에 배치되는지 확인하세요.

var app = builder.Build(); // 1. NGINX/Cloudflare 로드 밸런서 뒤에 있는 경우 실제 IP가 추출되는지 확인하십시오 app.UseForwardedHeaders(); // 2. 악성 트래픽을 조기에 차단하십시오 app.UseMiddleware<ProxyTracer.Security.ProxyTracerMiddleware>(); app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.MapControllers(); app.Run();
최종 수정일: