首页  编辑  

Java SSL连接MongoDB数据库

Tags: /Java/   Date Created:
Java中 SSL 连接MangoDB数据库
org.springframework.dao.DataAccessResourceFailureException: Timed out after 30000 ms while waiting to connect. Client view of cluster state is {type=UNKNOWN, servers=[{address=www.abc.com:12708, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSocketWriteException: Exception sending message}, caused by {javax.net.ssl.SSLHandshakeException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target}, caused by {sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target}, caused by {sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target}}]; nested exception is com.mongodb.MongoTimeoutException: Timed out after 30000 ms while waiting to connect. Client view of cluster state is {type=UNKNOWN, servers=[{address=www.abc.com:12708, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSocketWriteException: Exception sending message}, caused by {javax.net.ssl.SSLHandshakeException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target}, caused by {sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target}, caused by {sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target}}]
这是因为你使用了自签名证书,而自签名的根证书不在Java的CA证书列表中,导致无法验证证书。
解决办法,导入你的自签名根证书到Java的根证书列表中即可:
  1. 如果是PEM证书,则先使用 openssl转换 PEM 文件为 CER 证书,如果不是PEM则可以跳过这个步骤:
    openssl x509 -inform PEM -outform DER -in PEM路径和文件名.pem -out 自己给个名字.cer
  2. 到你的 Java JDK目录,例如  IDEA安装目录下\jbr\lib\security 目录,如果你使用的是 OpenJDK,那么请到 Open JDK对应目录下运行指令:
    ..\..\bin\keytool.exe -import -alias 自己给个别名  -file 自己给个名字.cer -keystore cacerts
    密码为 changeit 
  3. 重启 Idea 即可。
"msg": "Exception authenticating MongoCredential{mechanism=SCRAM-SHA-256, userName='username', source='dbname', password=<hidden>, mechanismProperties=<hidden>}",
解决办法:在连接字符串上增加参数 "authSource=admin" 。

"msg": "Query failed with error code 13 with name 'Unauthorized' and error message 'not authorized on dbname to execute command { find: \"###\", filter: { name: \"###\", parentName: \"###\", level: \"###\", _class: { $in: [ \"###\" ] } }, $db: \"###\", $clusterTime: { clusterTime: \"###\", signature: { hash: \"###\", keyId: \"###\" } }, lsid: { id: \"###\" } }' on server www.abc.com:12708",
解决办法:你没有数据库的权限,请设置权限,或者请确认你的数据库名字是否正确。