Spring Boot连接到带SSL的PostgreSQL

11

我有一个使用Postgresql 9.6作为数据库的Spring Boot应用程序(版本2.1.1)。 我必须通过SSL连接到数据库并使用sslmode=verify-ca。 到目前为止,我所做的是在Application.properties文件中设置属性。

spring.datasource.url=jdbc:postgresql://`url`:`port`/`db`?
    ssl=true&
    sslmode=verify-ca&
    sslcert=`path_to_client_cert`&
    sslkey=`path_to_client_key`&
    sslrootcert=`path_to_ca_cert`

有没有一种方法可以在其他Spring属性中指定SSL属性而不是在连接URL中指定?

另外,有没有可能指定证书的相对路径,而不是使用绝对路径?

4个回答

5

我将证书放在 src/main/resources 中,并使用了相对路径,这样做可以正常工作:

jdbc:postgresql://db_host:db_port/db_name?
    sslmode=require&
    sslrootcert=`my_root_certificate.crt`

看起来URL是指定这些参数的唯一位置。您也可以使用环境变量进行插值。


这个 ` 在这个 JDBC 连接字符串中真的有效吗? - Yiling

3

我无法使用org.postgresql.ssl.NonValidatingFactory使其工作。

我在连接字符串的末尾添加了?sslmode=verify-full

默认情况下,它将使用org.postgresql.ssl.LibPQFactory

默认情况下,它会查找 $HOME/.postgresql/ 下的证书,如下所示:

org.postgresql.PGProperty.SSL_ROOT_CERT; root.crt
org.postgresql.PGProperty.SSL_CERT; postgresql.crt
org.postgresql.PGProperty.SSL_KEY; postgresql.pk8

将您的私钥转换为pk8格式:

openssl pkcs8 -topk8 -inform PEM -outform DER -in postgresql.key -out postgresql.pk8 -nocrypt

1

如果您正在使用GCP,请按照以下步骤连接cloudsql-postgres和spring boot。

我已经解决了这个问题。

在云中创建数据库并创建客户端证书。

  1. 在GCP数据库中应配置"仅允许SSL连接"。

  2. GCP为您提供3个文件:client-cert.pem、client-key.pem和server-ca.pem。

  3. 必须使用以下命令将客户端密钥转换为pk8: sudo openssl pkcs8 -topk8 -inform PEM -outform DER -in client-key.pem -out client-key.pk8 -nocrypt

  4. 这些文件必须保存在运行TB的服务器上的某个位置,我使用的文件夹是/root/pgcerts/,因为我已经在使用它进行其他操作(此文件夹由我创建)

  5. 必须授予权限: chmod o+r /root/pgcerts/client-key.pk8

application.properties文件的POSTGRESQL部分,必须使用以下信息。


database=postgresql
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.PostgreSQLDialect
spring.jpa.database-platform= org.hibernate.dialect.PostgreSQLDialect
spring.jpa.hibernate.show-sql= true
spring.datasource.username= <username>
spring.datasource.password= <password>
spring.sql.init.mode=always
spring.datasource.url= jdbc:postgresql://DATABASEIP:5432/postgres?sslmode=require&sslrootcert=/root/pgcerts/server-ca.pem&sslcert=/root/pgcerts/client-cert.pem&sslkey=/root/pgcerts/client-key.pk8

1
如果您正在使用Hikari,可以像这样设置属性:
spring.datasource:
  url: jdbc:postgresql://host:port/db
  hikari.data-source-properties:
    ssl: true
    sslmode: verify-ca
    sslcert: path_to_client_cert
    sslkey: path_to_client_key
    sslrootcert: path_to_ca_cert

相对路径将起作用。该值只是传递给new FileInputStream(String)

如果您需要更复杂的内容,例如加载类路径资源,则需要提供自定义(或不同的)sslfactory

例如,{{link1:org.postgresql.ssl.SingleCertValidatingFactory}}支持classpath: URL。


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