Man In The Middle in Aspnet with Bearer Tokens
Man In The Middle in Aspnet with Bearer Tokens — how this specific combination creates or exposes the vulnerability
In an ASP.NET application, using Bearer Tokens over unencrypted or improperly validated channels creates a classic Man In The Middle (MitM) scenario. Bearer Tokens rely on the assumption that only the token holder can present it; if an attacker intercepts the token in transit, they can impersonate the legitimate client. This commonly occurs when HTTPS is absent, when TLS is misconfigured (e.g., using weak protocols or accepting invalid certificates), or when token transmission occurs over insecure channels such as HTTP or before TLS is fully established.
ASP.NET applications that accept tokens via the Authorization header are susceptible if requests traverse networks where an attacker can position themselves. For example, consider a mobile client or a Single Page Application (SPA) that sends an Authorization header like Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9... over HTTP. An attacker on the same network can capture this header and reuse the token to gain unauthorized access. Even when HTTPS is used, insufficient certificate validation in client code can allow an attacker to perform SSL stripping or present a fraudulent certificate, enabling token interception.
The risk is compounded when token handling, storage, or validation logic in ASP.NET does not enforce strict transport security. For instance, if an API endpoint does not require secure transport (e.g., does not enforce HSTS or reject non-TLS requests), or if the token is logged inadvertently in server-side diagnostics, the token can be exposed. Additionally, misconfigured CORS policies or insecure redirects can open paths for token leakage through malicious intermediaries. Attack patterns like session hijacking and credential theft often exploit these weak links, leading to unauthorized API access and potential data exfiltration.
Real-world examples align with common weaknesses enumerated in the OWASP API Security Top 10, such as insufficient encryption and lack of transport layer integrity. Without enforced HTTPS and proper token validation, an ASP.NET application behaves as though it is operating in a clear-text environment, making Bearer Tokens effectively public. Security scanners like middleBrick detect such misconfigurations by analyzing unauthenticated attack surfaces and identifying endpoints that accept Bearer Tokens without enforcing encryption and strict validation, providing prioritized findings and remediation guidance to close these gaps.
Bearer Tokens-Specific Remediation in Aspnet — concrete code fixes
Remediation centers on enforcing HTTPS, validating tokens securely, and ensuring tokens are never transmitted or stored insecurely. Below are concrete code examples for an ASP.NET Core application that demonstrate secure handling of Bearer Tokens.
Enforce HTTPS and Require Secure Transport
Configure the application to reject non-TLS requests and enforce HTTPS for all endpoints, especially those handling authentication.
// Program.cs
var builder = WebApplication.CreateBuilder(args);
// Enforce HTTPS redirection and require HTTPS in production
builder.Services.AddHttpsRedirection(options =>
{
options.HttpsPort = 443;
});
// Require authorization for all endpoints by default
builder.Services.AddAuthorization();
var app = builder.Build();
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
Secure Bearer Token Validation in Middleware
Use built-in authentication mechanisms to validate Bearer Tokens. Avoid manual parsing of the Authorization header.
// Program.cs with JWT Bearer authentication
builder.Services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = "Bearer";
options.DefaultChallengeScheme = "Bearer";
}).AddJwtBearer("Bearer", options =>
{
options.Authority = "https://your-identity-provider.com";
options.Audience = "your-api-audience";
options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = "https://your-identity-provider.com",
ValidAudience = "your-api-audience",
IssuerSigningKey = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(
System.Text.Encoding.UTF8.GetBytes("YourVeryStrongAndSecretKeyThatIsLongEnough")
)
};
});
var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();
Transmit Tokens Only Over HTTPS
Ensure that clients always send Bearer Tokens via the Authorization header over HTTPS. Example of a correct client request:
// Example using HttpClient in a client application
var handler = new HttpClientHandler();
// Ensure the handler is configured to validate server certificates
handler.ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator; // NOT for production
using var client = new HttpClient(handler);
client.BaseAddress = new Uri("https://api.example.com/");
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...");
var response = await client.GetAsync("/secure-endpoint");
response.EnsureSuccessStatusCode();
In production, remove the custom certificate validation and rely on the system's trusted certificate store to prevent MitM attacks.
Additional Hardening Measures
- Enable HTTP Strict Transport Security (HSTS) to force browsers to use HTTPS.
- Set Secure and HttpOnly flags on any cookies that might be used alongside token-based flows.
- Implement short token lifetimes and use refresh tokens securely to reduce the impact of a leaked token.
- Validate token audiences and issuers strictly to prevent token substitution across services.
These practices reduce the attack surface for MitM when Bearer Tokens are used in ASP.NET applications. Tools like middleBrick can verify that these controls are in place by scanning endpoints and checking for missing HTTPS enforcement, improper token validation, and insecure transmission patterns.