配置Spring连接MySQL时如何启用SSL

10

我正在从我的Java应用程序通过SSL连接到MySQL。我已经配置了MYSQL以支持SSL并生成客户端证书。我已将服务器CA证书和客户端证书导入密钥库。这是我目前代码的样子

    String url = "jdbc:mysql://127.0.0.1:3306/MySampleDb? verifyServerCertificate =true&useSSL=true&requireSSL=true"

    System.setProperty("javax.net.ssl.keyStore","/home/cert/keystore");
    System.setProperty("javax.net.ssl.keyStorePassword","password");
    System.setProperty("javax.net.ssl.trustStore","/home/cert/truststore");
    System.setProperty("javax.net.ssl.trustStorePassword","password");

    Class.forName("com.mysql.jdbc.Driver");
    con = DriverManager.getConnection(url, user, password);

我想使用Spring和C3p0连接到启用SSL的MYSQL数据库。这是我的Spring配置文件,它从jdbc.properties文件中读取参数。

<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
    <property name="driverClass" value="${jdbc.driver}"/>
    <property name="jdbcUrl" value="${jdbc.url}"/>
    <property name="user" value="${jdbc.username}"/>
    <property name="password" value="${jdbc.password}"/>
    ........
</bean>
我该如何配置Spring以设置属性verifyServerCertificate=true、useSSL=true、requireSSL=true?同时,在Spring配置文件中设置keyStore和trustStore值是否可行?
3个回答

15

jdbc.properties文件中jdbc.url的值必须为:

jdbc:mysql://127.0.0.1:3306/MySampleDb?verifyServerCertificate=true&useSSL=true&requireSSL=true

这些参数必须直接添加到MySQL的URL中。keyStoretrustStore的参数应该在启动JVM时传递,如下所示:

-Djavax.net.ssl.keyStore=path_to_keystore_file
-Djavax.net.ssl.keyStorePassword=password
-Djavax.net.ssl.trustStore=path_to_truststore_file
-Djavax.net.ssl.trustStorePassword=password

可以使用Spring来设置系统属性,但我从不使用它,因为它太麻烦了。


8

不必将 keyStoretrustStore 传递给 java 程序或设置任何系统属性,因为可以通过每个连接的连接属性实现!

因此,您可以为不同的连接(和应用程序,如果您在应用程序服务器中)使用不同的证书。

原始答案:https://dev59.com/2FsV5IYBdhLWcg3w-iwC#51879119 相关部分:

jdbc:mysql://example.com:3306/MYDB?verifyServerCertificate=true&useSSL=true&requireSSL=true&clientCertificateKeyStoreUrl=file:cert/keystore.jks&clientCertificateKeyStorePassword=123456&trustCertificateKeyStoreUrl=file:cert/truststore.jks&trustCertificateKeyStorePassword=123456

它已被记录:


1
您可以使用基于Java的配置来配置DataSourceuseSSlrequireSSLverifyServerCertificate属性。通过DataSource类的addDataSourceProperty方法,您可以像下面的代码片段所示一样具有此能力(您可以将HikariDataSource替换为C3p0实例)。
MySQL Connector/J公开了密钥库的配置属性(例如trustCertificateKeyStoreUrl),因此我认为这些属性也可以使用addDataSourceProperty进行配置。
我不知道XML配置模式是否提供与addDataSourceProperty相对应的标记。
public DataSource createPslDataSource(final MyDataSourceProperties myDataSourceProperties) {

    HikariDataSource dataSource = new HikariDataSource();

    dataSource.addDataSourceProperty("useSSL", true);
    dataSource.addDataSourceProperty("requireSSL", true);
    dataSource.addDataSourceProperty("verifyServerCertificate", true);

    dataSource.setJdbcUrl(myDataSourceProperties.getJdbcUrl());
    dataSource.setUsername(myDataSourceProperties.getUsername());
    dataSource.setPassword(myDataSourceProperties.getPassword());

    return dataSource;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接