GuardAPI Logo
GuardAPI

Fix NoSQL Injection in Spring Boot

NoSQL injection in Spring Boot environments typically targets MongoDB through improper use of MongoTemplate or raw JSON queries. When untrusted input is concatenated directly into a query string, attackers can inject operators like $gt, $ne, or $where to bypass authentication or dump the entire collection. If you aren't using parameterized abstractions, you're vulnerable.

The Vulnerable Pattern

@Service
public class UserService {
    @Autowired
    private MongoTemplate mongoTemplate;
public List<User> insecureSearch(String userInput) {
    // FATAL: String concatenation allows an attacker to inject JSON operators
    // Input: '" || 1==1 || "' returns all users
    String rawJson = "{ 'username': '" + userInput + "' }";
    Query query = new BasicQuery(rawJson);
    return mongoTemplate.find(query, User.class);
}

}

The Secure Implementation

The vulnerability stems from treating untrusted data as executable query logic. In the vulnerable example, an attacker can break out of the string literal and inject arbitrary MongoDB expressions. The fix involves using the Criteria API or parameterized @Query methods. These approaches utilize the underlying driver's ability to properly escape and type-check inputs, ensuring that a string like '{$ne: null}' is searched for as a literal string rather than being interpreted as a 'not equal' operator.

@Service
public class UserService {
    @Autowired
    private MongoTemplate mongoTemplate;
public List<User> secureSearch(String username) {
    // FIXED: Using Criteria API ensures input is treated as a literal value, not a command
    Query query = new Query(Criteria.where("username").is(username));
    return mongoTemplate.find(query, User.class);
}

}

// OR using Spring Data Repositories public interface UserRepository extends MongoRepository<User, String> { // FIXED: Parameter binding (?0) is handled safely by the driver @Query(”{ ‘username’: ?0 }”) List findByUsername(String username); }

System Alert • ID: 9030
Target: Spring Boot API
Potential Vulnerability

Your Spring Boot API might be exposed to NoSQL Injection

74% of Spring Boot 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.