Phishing Api Keys in Aspnet with Bearer Tokens
Phishing Api Keys in Aspnet with Bearer Tokens — how this specific combination creates or exposes the vulnerability
In ASP.NET applications, storing API keys as bearer tokens in configuration files or source code creates a phishing and leakage risk. Attackers commonly use social engineering to obtain developer credentials or access to repositories, then use those credentials to retrieve the keys. Because bearer tokens are static secrets, once phished they can be reused until explicitly rotated, enabling unauthorized API access without additional user interaction.
When API keys are embedded in string constants or JSON configuration sections without encryption, they become targets for phishing emails that trick developers into uploading files or sharing screenshots containing the tokens. If the application logs bearer tokens in diagnostic traces or error messages, those logs can be exfiltrated through log phishing or log injection techniques. The combination of weak access controls around configuration stores and insufficient transport-layer protections increases the likelihood that a phished token leads to a compromise of the API surface.
OWASP API Top 10 categories such as Broken Object Level Authorization (BOLA) and Data Exposure intersect with this risk: a phished bearer token may allow an attacker to traverse IDOR-prone endpoints by presenting a valid token that lacks per-request scope constraints. MiddleBrick scans detect these patterns by correlating unauthenticated API probing results with known authentication misconfigurations, highlighting endpoints that accept bearer tokens without adequate authorization checks.
Additionally, if bearer tokens are passed in query strings or non-HTTPS environments, network-level phishing or interception can occur. Even in HTTPS scenarios, improper certificate validation in the client can expose tokens to man-in-the-middle attacks. The presence of insecure defaults in ASP.NET Core projects, such as allowing insecure protocols or failing to enforce HTTPS redirection, compounds the impact of a phished token.
Because bearer tokens are long-lived credentials, continuous monitoring is required to detect anomalous usage after a successful phishing event. MiddleBrick’s continuous monitoring capabilities in the Pro plan can identify sudden spikes or geographic irregularities in token usage, providing alerts that help teams respond before widespread damage occurs.
Bearer Tokens-Specific Remediation in Aspnet — concrete code fixes
Remediation centers on avoiding hardcoded bearer tokens, enforcing HTTPS, and applying short lifetimes with rotation. Store sensitive values using ASP.NET Core’s user secrets during development and Azure Key Vault or environment variables in production. Use the Data Protection API for additional encryption at rest when storing tokens in application state.
Example of insecure code to avoid:
// Insecure: bearer token in source code
public static class ApiConfig
{
public const string BearerToken = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...";
}
Secure alternative using configuration and runtime retrieval:
// appsettings.json (not committed to source control)
{
"ApiSettings": {
"ServiceName": {
"BaseAddress": "https://api.example.com",
"Scope": "api.read"
}
}
}
// Program.cs
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddHttpClient("SecureApi", client =>
{
var baseAddress = builder.Configuration["ApiSettings:ServiceName:BaseAddress"];
client.BaseAddress = new Uri(baseAddress);
}).ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler
{
// Enforce HTTPS and avoid insecure defaults
CheckCertificateRevocationList = true
});
// Token retrieval via secure secret manager at runtime
builder.Services.AddAuthorization(options =>
{
options.AddPolicy("BearerPolicy", policy =>
{
policy.RequireAuthenticatedUser();
// Additional custom logic can validate token scopes here
});
});
var app = builder.Build();
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapGet("/call", async (IHttpClientFactory factory) =>
{
var client = factory.CreateClient("SecureApi");
var token = builder.Configuration["ApiSettings:ServiceName:TokenSource"];
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);
var response = await client.GetAsync("/v1/resource");
return Results.StatusCode((int)response.StatusCode);
}).RequireAuthorization("BearerPolicy");
app.Run();
Rotate bearer tokens on a defined schedule and immediately revoke compromised tokens. Use HTTP client factories to inject tokens dynamically rather than caching them in static fields. Validate inbound tokens on API gateways or middleware when applicable, and ensure that token scopes are minimal and scoped to the least privilege required by each endpoint.
For environments using Azure App Service or similar hosting, enable managed identities and avoid embedding connection strings or tokens in configuration. MiddleBrick’s scans will flag endpoints that accept bearer tokens without transport security or with overly permissive CORS settings, helping teams prioritize fixes.