logo

Database

Java Hardcoded Mongodb Credentials

Description

Identifies hardcoded MongoDB credentials in Java application code, specifically in MongoDB connection strings/URIs. Storing database credentials directly in source code is a security risk that could lead to unauthorized database access if the code is exposed through version control or other means.

Weakness:

359 - Sensitive information in source code - Credentials

Category: Information Collection

Detection Strategy

    Check if MongoDB-related libraries are imported (com.mongodb, org.mongodb, or org.springframework.data.mongodb)

    Look for MongoClientURI constructor calls in the code

    Extract the connection string passed to MongoClientURI

    Analyze the connection string to detect if it contains hardcoded credentials (username:password format)

    Report a vulnerability if credentials are found hardcoded in the MongoDB connection URI

Vulnerable code example

import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;

public class DatabaseConnection {
    public void connect() {
        // Insecure: Hardcoded credentials in connection string
        new MongoClient(new MongoClientURI("mongodb://admin:secret123@localhost:27017/db")); 
...

✅ Secure code example

import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import java.util.Optional;

public class DatabaseConnection {
    public void connect() {
        // Secure: Get credentials from environment variables
        String username = Optional.ofNullable(System.getenv("MONGODB_USER"))...