Use reflection to obtain data source connection information

   In the production environment, MySQL is provided to the application in the form of a cloud plug-in, and the connection credentials are controlled by the operation and maintenance and shielded from the application developer, which is inevitably inconvenient when needed. At this time, we can restore it by reflection. The code is as follows:

import java.lang.reflect.Field;
import org.apache.log4j.Logger;

public class CrackDbInfo {
	protected static final Logger log = Logger.getLogger(CrackDbInfo.class);

	/**
	 * Use reflection to obtain data source connection information
	 *
	 * @param dataSource
	 * @return
	 */
	public static String retriveCredentials(javax.sql.DataSource dataSource) {
		String result = null;
		try {
			Field host = dataSource.getClass().getDeclaredField("host");
			host.setAccessible(true);
			Object hostValue = host.get(dataSource);
			Field port = dataSource.getClass().getDeclaredField("port");
			port.setAccessible(true);
			Object portValue = port.get(dataSource);
			Field database = dataSource.getClass().getDeclaredField("database");
			database.setAccessible(true);
			Object databaseValue = database.get(dataSource);
			Field user = dataSource.getClass().getDeclaredField("user");
			user.setAccessible(true);
			Object userValue = user.get(dataSource);
			Field pwd = dataSource.getClass().getDeclaredField("password");
			pwd.setAccessible(true);
			Object pwdValue = pwd.get(dataSource);
			result = String
					.format("{\"user\": \"%s\", \"pwd\": \"%s\", \"host\": \"%s\", \"port\": %s, \"database\": \"%s\"}",
							userValue.toString(), pwdValue.toString(), hostValue.toString(),
							portValue.toString(), databaseValue.toString());
		} catch (NoSuchFieldException e) {
			log.error(e.getMessage(), e);
		} catch (SecurityException e) {
			log.error(e.getMessage(), e);
		} catch (IllegalArgumentException e) {
			log.error(e.getMessage(), e);
		} catch (IllegalAccessException e) {
			log.error(e.getMessage(), e);
		}
		return result;
	}
}

 

@see:http://lixuanbin.github.io/2016/06/30/hack-datasource-credentials-via-reflection/

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326762228&siteId=291194637