springboot 添加DbPasswordCallback

运行环境

  • SpringBoot版本 2.0.2.RELEASE

  • druid-spring-boot-starter版本 1.1.10

  • jdk 1.8

背景

直接将密码写在配置文件里面是不好的编码方式,容易造成数据库安全问题。所以比较好的方式是通过使用 `PasswordCallback`

这个接口,在数据库初始化的时候,动态去获取密码。

alibbaba的druid数据库连接池支持这样的获取密码。

yml配置

spring:
  datasource:
    druid:
      delivery:
        url: "jdbc:mysql://192.168.1.100:3306/demo?useUnicode=true&useSSL=false&characterEncoding=UTF-8"
        username: "root"
        password: ""
        connectionProperties: x=demo;y=xxxx
        driverClassName: com.mysql.jdbc.Driver

DbPasswordCallback继承

public class DbPasswordCallBack extends DruidPasswordCallback {

    private final static Logger logger = LoggerFactory.getLogger(DbPasswordCallBack.class);
    public DbPasswordCallBack() {

    }

    @Override
    public void setProperties(Properties properties) {
        super.setProperties(properties);

        String x = properties.getProperty("x");
        String y = properties.getProperty("y");
        if (x == null || y == null) {
            return;
        }
        String password = findPassword(x, y);
        if (password == null) {
            return;
        }
        setPassword(password.toCharArray());
    }

    private String findPassword(String x, String y) {
        //这里需要额外提供一个密码获取的服务,改写这里的url
        try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new URL(url + "?x=" + x + "&y=" + y).openStream()))) {
            String response = bufferedReader.readLine();
            JSONObject data = JSONObject.parseObject(response).getJSONArray("data").getJSONObject(0);
            return data.getString("password");
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new RuntimeException("HTTP request went wrong");
        }
        return null;
    }
}

DbPasswordCallback使用

@Bean(name = BEAN_NAME_DATA_SOURCE)
@ConfigurationProperties(CONFIG_PATH)
public DataSource initDataSource() {
    DruidDataSource build = DruidDataSourceBuilder.create().build();
    build.setPasswordCallback(new DbPasswordCallBack());
    return build;
}

results matching ""

    No results matching ""