公司安全策略,不允许代码里放密码,于是密码都在Vault里了。
Vault 介绍:
https://www.jianshu.com/p/267f2d9ae87e
依赖:
compile 'com.bettercloud:vault-java-driver:3.1.0'
这里的工具类,主要是读取Vault中已经存好的密码。
/** * Read password from Vault. <br /> * <ul>these property should be set by System.setProperty(key, value). * <li>spring.profiles.active, required</li> * <li>vault.roleId, required</li> * <li>vault.secretId, required</li> * <li>vault.cmdbRole, optional.</li> * </ul> * */ public class VaultRead { public static String VAULT_PROFILE = "spring.profiles.active"; public static String VAULT_ROLE_ID = "vault.roleId"; public static String VAULT_SECRET_ID = "vault.secretId"; public static String VAULT_CMDB_ROLE = "vault.cmdbRole"; private VaultConfig config; private String roleId; private String secretId; private VaultRead() { // set vault uri according to profile String profile = System.getProperty(VAULT_PROFILE, "develop"); String vaultUri; if (profile.indexOf("prod") >= 0) { vaultUri = "https://vault-prod.vault.test.net:443"; } else { vaultUri = "https://vault-stage.vault.test.net:443"; } try { this.config = new VaultConfig().address(vaultUri).build(); this.roleId = System.getProperty(VAULT_ROLE_ID); this.secretId = System.getProperty(VAULT_SECRET_ID); } catch (VaultException e) { e.printStackTrace(); } System.out.println("init vault, uri: " + vaultUri + ", roleId: " + roleId); } /** * get password for key from path. * @param path * @param key * @return */ public String getData(String path, String key) { try { Vault vault = new Vault(config); // auth by roleId & secretId AuthResponse auth = vault.auth().loginByAppRole(roleId, secretId); config.token(auth.getAuthClientToken()); // read data LogicalResponse response = vault.logical().read(path); System.out.println("path: " + path + ", key: " + key); return response.getData().get(key); } catch (Exception e) { String errMsg = e.getMessage(); if (errMsg != null && errMsg.indexOf("400") > 0) { System.err.println("vault login failed, " + errMsg); } else { e.printStackTrace(); } } return null; } // singleton pattern static class Helper { static VaultRead INSTANCE = new VaultRead(); // default vault data path static String DEFAULT_PATH; static { String profile = System.getProperty(VAULT_PROFILE, "develop"); String cmdbRole = System.getProperty(VAULT_CMDB_ROLE, "fds_hadoop"); DEFAULT_PATH = "secret/" + cmdbRole + "/" + profile; System.out.println("vault cmdbRole: " + cmdbRole + ", profile: " + profile); } } /** * get password for key from vault data path. * @param path * @param key * @return */ public static String get(String path, String key) { return Helper.INSTANCE.getData(path, key); } /** * get password for key from vault default data path. <br/> * default data path: secret/${vault.cmdbRole}/${spring.profiles.active} * @param key * @return */ public static String get(String key) { return Helper.INSTANCE.getData(Helper.DEFAULT_PATH, key); } }