I’m using the following code to initialize database connection:
public Connection getConnection() {
try {
if (null == connection) {
String driverName = "com.mysql.jdbc.Driver"; // MySQL MM JDBC driver
Class.forName(driverName);
// Create a connection to the database
String serverName = "localhost";
String database = "database";
String url = "jdbc:mysql://" + serverName + "/" + mydatabase; // a JDBC url
String username = "username";
String password = "password";
connection = DriverManager.getConnection(url, username, password);
}
return connection;
} catch (ClassNotFoundException cnfe) {
cnfe.printStackTrace();
} catch (SQLException sqle) {
sqle.printStackTrace();
}
throw new NullPointerException("Cannot establish database connection...");
}
and I know it’s bad practice to do it, also I ran FindBugs against the code, and got the security issue saying the following:
This code creates a database connect using a hardcoded, constant password. Anyone with access to either the source code or the compiled code can easily learn the password.
What’s the best way to initialize database connection without having this security breach?
The vast majority of Web Applications use a hard-coded username/password for their SQL connection. Checking production credentials into source control, or giving interns the ability to delete the production database is generally frowned upon. Production credentials should be protected, and only privileged employees should have access to them.
It is common for web applications to leak their configuration files. For example if a .xml file is stored in the webroot then it can be accessed remotely:
http://localhost/configs/db_config.xml.It is common practice to disallow access to your database (block tcp port 3306 for mysql). In fact this is a requirement of the PCI-DSS. Even if the username and password where to be obtained, it would be useless.