我已经在我的 spring boot 应用程序中启用了 ssl,并且每当我想使用像 googleapis 或 facebook 这样的 Rest 服务时,我都必须在信任库中添加证书。
我使用openssl获取证书:
openssl s_client -connect googleapis.com:443
然后我将它导入信任库:
keytool.exe -import -noprompt -trustcacerts -alias googleapis.com -file googleapis.com.cer -keystore app-server.p12 -storepass *****
问题是管理起来很不方便,每次证书过期我都得更新truststore里的证书。
此外,即使我添加了正确的证书,有时也会出现错误:
Caused by: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
我知道这些证书是有效的,那么是否可以自动信任它们而无需将它们添加到信任库中?
这是我的ssl配置
ssl:
enabled: true
key-store: classpath:keystore/app-server.p12
key-store-password: ******
key-alias: app-server
key-store-type: PKCS12
trust-store: classpath:keystore/app-server.p12
trust-store-password: *****
trust-store-type: PKCS12
keyStorePath: config/keystore/app-server.p12
我还必须在 main 方法中添加系统属性
private static String keyStorePath;
private static String keyStorePassword;
@Value("${server.ssl.keyStorePath}")
public void setKeyStorePath(String keyStorePath) {
ClientUiApplication.keyStorePath = keyStorePath;
}
@Value("${server.ssl.key-store-password}")
public void setKeyStorePassword(String keyStorePassword) {
ClientUiApplication.keyStorePassword = keyStorePassword;
}
public static void main(String[] args) {
SpringApplication.run(ClientUiApplication.class, args);
System.setProperty("javax.net.ssl.trustStore", keyStorePath);
System.setProperty("javax.net.ssl.trustStorePassword", keyStorePassword);
}
另一个重要的细节,我需要一个信任库,因为我使用通过 Keytool 生成的自签名证书。否则,我的服务无法相互通信。
最佳答案
你给代码:
public static void main(String[] args) {
SpringApplication.run(ClientUiApplication.class, args);
System.setProperty("javax.net.ssl.trustStore", keyStorePath);
System.setProperty("javax.net.ssl.trustStorePassword", keyStorePassword);
}
这意味着您强制 java 信任库成为您提供的信任库。默认信任库不再使用。
所以是的,您必须在此信任库中添加所有需要的根证书,才能避免出现您描述的问题。
为什么需要一个特定的信任库?
- 如果没有用,请将其删除。
- 如果您有必须信任的特定附加证书,最好将此证书添加到默认信任库(
jre/lib/security/cacerts
文件)
关于spring-boot - Spring boot ssl如何信任所有有效证书,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59485445/