Skip to content

Instantly share code, notes, and snippets.

@mstyura
Last active October 17, 2020 20:47
Show Gist options
  • Save mstyura/6e7cbbfa7356de2dfabfb889b88bf22c to your computer and use it in GitHub Desktop.
Save mstyura/6e7cbbfa7356de2dfabfb889b88bf22c to your computer and use it in GitHub Desktop.
An example of Akka HTTP configuration which makes it accept self signed certificate.
import akka.actor.ActorSystem;
import akka.http.javadsl.*;
import akka.http.javadsl.model.HttpRequest;
import com.typesafe.sslconfig.akka.AkkaSSLConfig;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.Optional;
public class Main {
public static void main(String[] args) {
/*
Example of Akka Http client accepting self signed certificate.
Tested with:
com.typesafe.akka:akka-stream_2.12:2.5.17
com.typesafe.akka:akka-actor_2.12:2.5.17
com.typesafe.akka:akka-http_2.12:10.1.5
*/
ActorSystem actorSystem = ActorSystem.create("client");
Http.get(actorSystem)
.singleRequest(
HttpRequest.GET("https://localhost:443/some_endpoint"),
unsafeHttpsContext(actorSystem))
.handle((response, error) -> {
if (error != null) {
System.out.println(error);
} else {
System.out.println(response);
}
return "";
})
.toCompletableFuture()
.join();
}
private static HttpsConnectionContext unsafeHttpsContext(ActorSystem actorSystem) {
final AkkaSSLConfig badSslConfig = AkkaSSLConfig
.get(actorSystem)
.convertSettings(s -> s
.withLoose(s
.loose()
//.withAcceptAnyCertificate(true) // https://github.com/lightbend/ssl-config/issues/69
.withDisableHostnameVerification(true)));
SSLContext sslContext = null;
try {
sslContext = SSLContext.getInstance("TLS");
sslContext.init(
null,
new TrustManager[]{new UnsafeTrustManager()},
null);
} catch (KeyManagementException | NoSuchAlgorithmException e) {
e.printStackTrace();
}
return ConnectionContext.https(
sslContext,
Optional.of(badSslConfig),
Optional.empty(),
Optional.empty(),
Optional.empty(),
Optional.empty());
}
private static final class UnsafeTrustManager implements X509TrustManager {
@Override
public void checkClientTrusted(java.security.cert.X509Certificate[] x509Certificates, String s) throws java.security.cert.CertificateException {
}
@Override
public void checkServerTrusted(java.security.cert.X509Certificate[] x509Certificates, String s) throws java.security.cert.CertificateException {
}
@Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new java.security.cert.X509Certificate[0];
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment