Skip to Content
DocumentationEnvironnements BackendASP.NET Core (C#)

C# (ASP.NET Core)

Pour les environnements d'entreprise Microsoft, l'intégration de ProxyTracer directement dans le pipeline de requêtes HTTP ASP.NET Core garantit que le trafic malveillant est rejeté avant qu'il ne déclenche le routage, la liaison de modèle ou les requêtes de base de données.

L'Intergiciel

Cette implémentation utilise System.Text.Json pour une désérialisation ultra-rapide, impose un délai d'attente strict via HttpClient, et court-circuite le pipeline avec une réponse 403 Forbidden s'il est signalé.

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"); // Reusable client with strict 500ms timeout _httpClient = new HttpClient { Timeout = TimeSpan.FromMilliseconds(500) }; } public async Task InvokeAsync(HttpContext context) { // 1. Extract the IP (Requires app.UseForwardedHeaders() configured in Program.cs) var ip = context.Connection.RemoteIpAddress?.ToString(); // Skip local development IPs if (!string.IsNullOrEmpty(ip) && ip != "127.0.0.1" && ip != "::1") { try { // 2. Query ProxyTracer API asynchronously 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. Drop the connection if a proxy/VPN is detected 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 the request pipeline } } } catch (Exception ex) { // Fail open: Log the error and allow the request through _logger.LogWarning($"ProxyTracer validation failed: {ex.Message}"); } } // 4. Traffic is clean, proceed to controllers await _next(context); } // Lightweight struct mapping exactly to the {"proxy": true|false} response private class ProxyTracerResult { [JsonPropertyName("proxy")] public bool Proxy { get; set; } } } }

Configuration

Pour activer la protection, enregistrez l'intergiciel dans votre fichier Program.cs. Assurez-vous qu'il est placé après UseForwardedHeaders mais avant UseRouting et UseAuthentication.

var app = builder.Build(); // 1. Ensure real IPs are extracted if behind an NGINX/Cloudflare load balancer app.UseForwardedHeaders(); // 2. Drop malicious traffic early app.UseMiddleware<ProxyTracer.Security.ProxyTracerMiddleware>(); app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.MapControllers(); app.Run();
Last updated on