C# (ASP.NET Core)
For enterprise Microsoft environments, integrating ProxyTracer directly into the ASP.NET Core HTTP request pipeline ensures that malicious traffic is rejected before it triggers routing, model binding, or database queries.
The Middleware
This implementation uses System.Text.Json for ultra-fast deserialization, enforces a strict timeout via HttpClient, and short-circuits the pipeline with a 403 Forbidden response if flagged.
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
To activate the protection, register the middleware in your Program.cs file. Ensure it is placed after UseForwardedHeaders but before UseRouting and 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