简体   繁体   中英

Secure connection to mysql with SSL using BasicDataSource

I'm attempting to secure MySQL connections in my application with SSL. The relevant code I have as of now:

    BasicDataSource dataSource = new BasicDataSource();
    dataSource.setUsername(connectorConfig.getUser());
    dataSource.setPassword(connectorConfig.getPassword());
    String uri = connectorConfig.getConnectURI();
    dataSource.setUrl(uri);
    dataSource.setValidationQuery(getValidationQuery());
    dataSource.setTestOnBorrow(true);
    datasource.setDriverClassLoader(getClass().getClassLoader());
    datasource.setDriverClassName("com.mysql.jdbc.Driver");

    System.setProperty("javax.net.ssl.keyStore", "/Users/xx/xx/client.jks");
    System.setProperty("javax.net.ssl.keyStorePassword", "xx");
    System.setProperty("javax.net.ssl.trustStore", "/Users/xx/xx/server.jks");
    System.setProperty("javax.net.ssl.trustStorePassword", "xx");

    final DBI dbi = new DBI(datasource);

I'm using the DBCP2 BasicDataSource for datasource management and JDBI for executing queries. However, the above code does not work as I get the following error while attempting to establish connection to the mysql server:

Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

Any thoughts on how do I go about providing the SSL context parameters to the MySQL server in this case?

PS: I believe that my SSL configuration is correct as I was able to connect to the MySQL server using the client keystore from the commandline.

You can add the server's certificate in your truststore, but first check it's not already there with a keytool command. If it's still not working, use the debug property ( -Djavax.net.debug=all ) then we will check in the output what truststore you're really using, and what certificates are exchanged.

Figured out that System.setProperty is not the right approach to provide the parameters in my usecase. Switched BasicDataSource with MysqlDataSource which provides a way to specify the keystore params using setClientCertificateXX() and setTrustCertificateXX() methods and it seems to be working now.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM