Phishing Api Keys in Aspnet
How Phishing API Keys Manifests in ASP.NET
Phishing API keys in ASP.NET applications typically exploit the framework's authentication and authorization mechanisms to intercept or misuse credentials. Attackers often target the default ASP.NET Core Identity system, which handles user authentication through cookie-based sessions or JWT tokens. A common phishing pattern involves intercepting API keys during the authentication flow, especially when developers use insecure patterns like passing API keys in query strings or headers without proper validation.
One specific ASP.NET vulnerability occurs when developers implement custom authentication middleware that fails to validate the origin of API key requests. For example, an attacker might create a malicious endpoint that mimics legitimate API authentication, tricking users into submitting their credentials. This is particularly dangerous in ASP.NET applications that expose multiple API endpoints without proper CORS configuration or origin validation.
Another manifestation involves token replay attacks in ASP.NET Web API controllers. If an application doesn't implement proper token expiration and rotation policies, attackers can capture valid API keys through man-in-the-middle attacks or phishing pages and reuse them indefinitely. This is especially problematic in ASP.NET applications that use symmetric encryption for JWT tokens without proper key rotation mechanisms.
ASP.NET's model binding can also be exploited for API key phishing. Attackers might craft requests that leverage model binding vulnerabilities to extract API keys from request bodies or headers. This is particularly effective in applications that use complex model hierarchies without proper validation of nested properties.
ASP.NET-Specific Detection
Detecting phishing API keys in ASP.NET applications requires a multi-layered approach that combines static analysis with runtime monitoring. Using middleBrick's API security scanner, developers can identify several ASP.NET-specific vulnerabilities related to API key handling.
The scanner examines ASP.NET Core's authentication middleware configuration, looking for insecure patterns such as:
// Vulnerable pattern - no origin validation
app.UseAuthentication(new AuthenticationOptions {
DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme
});
middleBrick specifically tests for ASP.NET's default token validation behavior, checking if applications properly validate token issuers and audiences. The scanner also examines the Startup.cs or Program.cs files for insecure authentication configurations.
Runtime detection involves monitoring ASP.NET's request pipeline for suspicious API key patterns. This includes tracking:
- API keys appearing in URLs or query strings
- Repeated authentication failures from the same IP
- API key usage patterns that deviate from normal behavior
- Requests with missing or malformed authentication headers
- Cross-origin API key submissions
middleBrick's black-box scanning approach tests these vulnerabilities without requiring source code access. The scanner sends crafted requests to ASP.NET endpoints, attempting to trigger authentication bypasses and API key extraction vulnerabilities.
For ASP.NET Web API specifically, the scanner checks for insecure attribute usage:
// Vulnerable - allows anonymous access without proper validation
[AllowAnonymous]
public class InsecureController : ControllerBase
{
[HttpGet("api/data")]
public IActionResult GetData()
{
// No API key validation
return Ok(_dataService.GetData());
}
}
ASP.NET-Specific Remediation
Securing ASP.NET applications against API key phishing requires implementing several framework-specific security measures. The first step is configuring proper authentication middleware with strict validation policies.
For JWT-based authentication, use ASP.NET Core's built-in token validation with explicit issuer and audience validation:
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidIssuer = Configuration["Jwt:Issuer"],
ValidateAudience = true,
ValidAudience = Configuration["Jwt:Audience"],
ValidateLifetime = true,
ClockSkew = TimeSpan.Zero
};
});
Implement API key rotation policies using ASP.NET Core's distributed caching for token revocation:
public class ApiKeyService
{
private readonly IDistributedCache _cache;
public async Task ValidateApiKeyAsync(string apiKey)
{
var cachedKey = await _cache.GetStringAsync($"apikey:{apiKey}");
if (cachedKey == null) return false;
// Check expiration and rotation policies
var keyData = JsonSerializer.Deserialize<ApiKeyData>(cachedKey);
if (keyData.LastRotated < DateTime.UtcNow.AddDays(-30))
{
// Force rotation for old keys
return false;
}
return true;
}
}
Secure your ASP.NET controllers using attribute-based authorization with custom policies:
services.AddAuthorization(options =>
{
options.AddPolicy("ApiKeyPolicy", policy =>
{
policy.Requirements.Add(new ApiKeyRequirement());
policy.AuthenticationSchemes.Add(JwtBearerDefaults.AuthenticationScheme);
});
});
public class ApiKeyRequirement : IAuthorizationRequirement
{
public class Handler : AuthorizationHandler<ApiKeyRequirement>
{
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, ApiKeyRequirement requirement)
{
var apiKey = context.Resource as string;
if (!string.IsNullOrEmpty(apiKey) && ApiKeyService.Validate(apiKey))
{
context.Succeed(requirement);
}
return Task.Completed();
}
}
}
Implement CORS policies to prevent cross-origin API key phishing attempts:
services.AddCors(options =>
{
options.AddPolicy("ApiPolicy", builder =>
{
builder.WithOrigins("https://yourdomain.com")
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials();
});
});
For ASP.NET Web API, use action filters to validate API keys before controller execution:
public class ApiKeyAuthAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext context)
{
var apiKey = context.HttpContext.Request.Headers["x-api-key"];
if (string.IsNullOrEmpty(apiKey) || !ApiKeyService.Validate(apiKey))
{
context.Result = new UnauthorizedObjectResult("Invalid API key");
}
}
}
Frequently Asked Questions
How can I test my ASP.NET API for phishing vulnerabilities?
middlebrick scan https://yourapi.com from the CLI or integrate it into your CI/CD pipeline using the GitHub Action. The scanner tests 12 security categories including authentication, input validation, and data exposure specific to ASP.NET applications.