Nosql Injection in Aspnet with Bearer Tokens
Nosql Injection in Aspnet with Bearer Tokens — how this specific combination creates or exposes the vulnerability
Nosql Injection occurs when user-controlled input is improperly used to construct NoSQL queries, allowing an attacker to alter query logic. In an ASP.NET application that relies on bearer token authentication, the token itself is often parsed and used to scope data access (for example, to enforce tenant or user boundaries). If the token value or claims derived from it are concatenated into a NoSQL query without proper validation or parameterization, the token context can be manipulated to bypass authorization or extract other tenants’ data.
Consider an ASP.NET Core service that uses a bearer token to identify the tenant (e.g., via a claim like tenant_id) and builds a MongoDB filter by string interpolation:
// Example: vulnerable string-based NoSQL query construction
var tenantId = User.FindFirst("tenant_id")?.Value;
var filter = "{ 'tenantId': '" + tenantId + "', 'status': 'active' }";
var results = collection.Find(filter).ToList();
An attacker who can influence the token’s tenant_id claim (via token substitution, a malicious issuer, or a compromised token) can change the filter to always match, for instance:
{ 'tenantId': { '$ne': null }, 'status': 'active' }
This is a classic BOLA/IDOR pattern enabled by the trust placed in bearer token claims. The API may return documents across tenants because the query logic was overridden. Additionally, if the application reflects token claims in responses or logs, it may inadvertently expose sensitive identity information useful for SSRF or privilege escalation attempts.
Because middleBrick tests unauthenticated attack surfaces, it can detect scenarios where NoSQL injection is possible even when bearer tokens are required for access. The scanner’s BOLA/IDOR and Unsafe Consumption checks, alongside Input Validation and Data Exposure checks, highlight how malformed or unexpected token values can manipulate query behavior. Findings include concrete evidence such as query structures returned by the endpoint and mappings to frameworks like OWASP API Top 10 and PCI-DSS controls.
Bearer Tokens-Specific Remediation in Aspnet — concrete code fixes
Secure handling of bearer tokens in ASP.NET requires treating token-derived data as untrusted input and avoiding direct concatenation into NoSQL queries. Use parameterized queries or expression-based filters, validate and constrain token claims, and enforce tenant isolation at the data access layer.
1. Use parameterized or expression-based queries
Instead of building query strings, use the driver’s filter builders. For MongoDB in ASP.NET, prefer FilterDefinition over raw strings:
// Safe: using the MongoDB FilterDefinition builder
var tenantId = User.FindFirst("tenant_id")?.Value;
if (string.IsNullOrEmpty(tenantId))
{
return Unauthorized();
}
var filter = Builders<BsonDocument>.Filter.And(
Builders<BsonDocument>.Filter.Eq("tenantId", tenantId),
Builders<BsonDocument>.Filter.Eq("status", "active")
);
var results = collection.Find(filter).ToList();
2. Validate and constrain claims from bearer tokens
Validate the format and values of claims before use. For example, ensure tenant_id matches an expected pattern and is a known tenant:
// Validate tenant claim format and existence
var tenantId = User.FindFirst("tenant_id")?.Value;
if (!Guid.TryParse(tenantId, out var tid) || tid == Guid.Empty)
{
return Unauthorized();
}
// Use tid in parameterized queries only
3. Enforce tenant isolation in the data access service
Centralize query construction so token-derived values are never directly interpolated. A service wrapper can enforce scoping:
public class TenantScopedService
{
private readonly IMongoCollection<BsonDocument> _collection;
public TenantScopedService(IMongoDatabase database, IHttpContextAccessor httpContextAccessor)
{
_collection = database.GetCollection<BsonDocument>("items");
var tenantId = httpContextAccessor.HttpContext?.User.FindFirst("tenant_id")?.Value
?? throw new UnauthorizedAccessException("Tenant ID missing");
// Store tenantId for use in safe query methods
}
public List<BsonDocument> GetActiveItems()
{
var filter = new BsonDocument
{
{ "tenantId", /* tenantId captured in constructor */ },
{ "status", "active" }
};
return _collection.Find(filter).ToList();
}
}
These practices reduce the risk of token-derived input manipulating NoSQL query logic. They align with OWASP API Top 10 categories such as Broken Object Level Authorization and Injection, and support compliance mappings referenced in middleBrick reports. The CLI (middlebrick scan <url>) and GitHub Action can validate that your endpoints follow these patterns; the dashboard tracks improvements over time.