我正在使用以下代码初始化数据库连接:
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...");
}
而且我知道这样做是不好的做法,而且我针对该代码运行了
FindBugs
,并遇到了如下安全问题: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.
在没有此安全漏洞的情况下初始化数据库连接的最佳方法是什么?
最佳答案
绝大多数Web应用程序在其SQL连接中都使用硬编码的用户名/密码。通常不赞成将生产凭证检查到源代码控制中,或者赋予实习生删除生产数据库的能力。生产凭证应受到保护,只有特权员工才能访问它们。
Web应用程序通常会泄漏其配置文件。例如,如果.xml文件存储在webroot中,则可以远程访问它:http://localhost/configs/db_config.xml
。
通常的做法是禁止访问您的数据库(对于mysql,阻止tcp端口3306)。实际上,这是PCI-DSS的要求。即使要获取用户名和密码,也将毫无用处。