我在Spring Boot应用程序中进行了集成测试,有些测试需要从Keycloak获取令牌。每次通信都是通过带有自签名证书的SSL进行的。
启动这些测试时,我遇到了异常:
SunCertPathBuilderException: unable to find valid certification path to requested target
问题似乎类似于Accept server's self-signed ssl certificate in Java client,但该解决方案对我不起作用。
这是我获得令牌的地方:
private AccessTokenResponse getToken() throws GeneralSecurityException {
Keycloak keycloak = Keycloak.getInstance(keycloakAuthServerUrl, keycloakRealm,
login, password, keycloakResource, keycloakCredentialsSecret);
return keycloak.tokenManager().getAccessToken();
}
答案 0 :(得分:0)
根据Accept server's self-signed ssl certificate in Java client中的建议,创建一个自定义信任管理器:
import javax.net.ssl.X509TrustManager;
public class TestTrustManager implements X509TrustManager {
@Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new java.security.cert.X509Certificate[0];
}
@Override
public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
}
@Override
public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
}
}
然后将其添加到密钥库“构造函数”中:
private AccessTokenResponse getToken() throws GeneralSecurityException {
// Install the all-trusting trust manager
SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, new TrustManager[] { new TestTrustManager() }, new java.security.SecureRandom());
Keycloak keycloak = Keycloak.getInstance(keycloakAuthServerUrl, keycloakRealm,
login, password, keycloakResource, keycloakCredentialsSecret, sslContext); // <--- !!! ADD IT HERE !!!
return keycloak.tokenManager().getAccessToken();
}