GuardAPI Logo
GuardAPI
Automated Security Protocol

How to fix NoSQL Injection
in .NET 8 Web API

Executive Summary

NoSQL injection in .NET 8 isn't just a theory—it's a critical failure in how developers handle MongoDB or CosmosDB drivers. If you are concatenating strings or using BsonSerializer.Deserialize on untrusted input to build filters, you are wide open. An attacker can inject operators like $ne, $gt, or $where to bypass authentication or exfiltrate the entire collection. Secure your Web API by ditching raw BSON strings for type-safe builders.

The Vulnerable Pattern

VULNERABLE CODE
[HttpGet("user")]
public async Task GetUser(string username, string password)
{
    // CRITICAL: String concatenation allows an attacker to pass: { "$ne": "" }
    // Resulting query: { "Username": { "$ne": "" }, "Password": { "$ne": "" } }
    var filter = "{ 'Username': '" + username + "', 'Password': '" + password + "' }";
    var user = await _collection.Find(BsonSerializer.Deserialize(filter)).FirstOrDefaultAsync();
    return Ok(user);
}

The Secure Implementation

The vulnerable code treats user input as part of the query structure, allowing an attacker to inject MongoDB operators that change the logic of the filter. By using the 'Builders.Filter' pattern in .NET, the driver treats the input as data (parameterization) rather than executable code. Additionally, always avoid the '$where' operator which executes arbitrary JavaScript, and ensure you are using the latest MongoDB.Driver NuGet package to benefit from built-in security patches.

SECURE CODE
[HttpGet("user")]
public async Task GetUser(string username, string password)
{
    // SECURE: Use the FilterDefinitionBuilder with LINQ expressions.
    // The driver automatically treats inputs as literal values, not command operators.
    var filter = Builders.Filter.And(
        Builders.Filter.Eq(u => u.Username, username),
        Builders.Filter.Eq(u => u.Password, password)
    );
var user = await _collection.Find(filter).FirstOrDefaultAsync();
return user is not null ? Ok(user) : NotFound();

}

System Alert • ID: 4110
Target: .NET 8 Web API API
Potential Vulnerability

Your .NET 8 Web API API might be exposed to NoSQL Injection

74% of .NET 8 Web API apps fail this check. Hackers use automated scanners to find this specific flaw. Check your codebase before they do.

RUN FREE SECURITY DIAGNOSTIC
GuardLabs Engine: ONLINE

Free Tier • No Credit Card • Instant Report

Verified by Ghost Labs Security Team

This content is continuously validated by our automated security engine and reviewed by our research team. Ghost Labs analyzes over 500+ vulnerability patterns across 40+ frameworks to provide up-to-date remediation strategies.