Spray-client sendReceive抛出SSLHandshakeException

时间:2015-03-11 19:30:03

标签: scala ssl spray-client

我正在尝试使用https将spray-client连接到受限制的rest api。问题是远程服务器的证书未注册为受信任,然后使用SSLHandshakeException拒绝简单的Get()连接,我很难找到有关如何使其工作的任何信息。这在某种程度上可以在我的本地机器上运行而无需改变某些东西。

我找到了关于如何将证书放入jvm truststore的教程,但是因为我使用的是dokku / docker,所以jfm实例的AFAIK是容器特定的(或?)。即使我将来可能在不同的机器上重新部署应用程序,我也希望在应用程序中定义它,而不是每次都设置jvm。

这是我第一次以编程方式面对SSL,因此我可能会对其工作原理做出错误的假设。你能帮忙吗?

2 个答案:

答案 0 :(得分:1)

我不是scala方面的专家,我从未使用过spray-client,但我会根据自己的Java经验来帮助你。

您有两个选项,使用服务器证书(SECURE)的密钥库中的TrustManagerFactory初始化SSLContext

File keyStoreFile = new File("./myKeyStore");
KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
ks.load(new FileInputStream(keyStoreFile), "keyStorePassword".toCharArray());
TrustManagerFactory tmf = TrustManagerFactory.getInstance("X509");
tmf.init(ks);
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null, tmf.getTrustManagers(), new java.security.SecureRandom());

创建一个接受任何证书的虚拟TrustManagerFactory(INSECURE)

import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.X509TrustManager;

public class DummyTrustManager implements X509TrustManager {

    public X509Certificate[] getAcceptedIssuers() {
        return new X509Certificate[0];
    }

    /* (non-Javadoc)
    * @see javax.net.ssl.X509TrustManager#checkClientTrusted(X509Certificate[], java.lang.String)
    */
    public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
    }
    /* (non-Javadoc)
    * @see javax.net.ssl.X509TrustManager#checkServerTrusted(X509Certificate[], java.lang.String)
    */
    public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
    }
}

通过这种方式初始化SSLContext(it is very similar in spray-client

SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null, new TrustManager[] { new DummyTrustManager() }, new java.security.SecureRandom());

我不知道Scala语法,但不应该很难将其翻译成你。

希望这有帮助。


编辑(由MatejBriškár建议):以上是正确的方法,但对于喷雾客户端来说并不是那么容易。要使sendReceive与SSL一起使用,您需要首先建立连接,然后将此连接传递给sendReceive

首先创建如上所述的隐式信任管理器。例如:

implicit def sslContext: SSLContext = { 
    val context = SSLContext.getInstance("TLS") 
    context.init(null, Array[TrustManager](new DummyTrustManager), new SecureRandom())
    context
}

请注意,此连接会在一段时间后超时,因此您可能需要更改此默认行为。

然后,您需要建立将使用此隐式的连接:

val connection = { 
    Await.result((IO(Http) ? HostConnectorSetup(host, port = 443, sslEncryption = true)).map { case HostConnectorInfo(hostConnector, _) => hostConnector }, timeout.duration) 
}

注意:host表示您尝试访问的网址。另外timeout来自此代码段之外。

最后,您可以使用sendReceive(connection)访问SSL加密主机。


注意:原始编辑有一个参考:

  

根据discussion online,问题将会得到解决。

然而,讨论是从2013年开始,现在是2016年。需要建立连接以使SSL工作的问题似乎仍然存在。不确定讨论是否相关。

答案 1 :(得分:1)

如果您只想以INSECURE方式执行此操作,那么这是我的2美分,我只是创建我的sendReceive方法来发送(HttpRequest,HostConnectorSetup)而不是HttpRequest

import java.security.SecureRandom
import java.security.cert.X509Certificate
import javax.net.ssl.{SSLContext, TrustManager, X509TrustManager}

import akka.actor.ActorRefFactory
import akka.io.IO
import akka.pattern.ask
import akka.util.Timeout
import spray.can.Http
import spray.can.Http.HostConnectorSetup
import spray.client.pipelining._
import spray.http.{HttpResponse, HttpResponsePart}
import spray.io.ClientSSLEngineProvider
import spray.util._

import scala.concurrent.ExecutionContext
import scala.concurrent.duration._


object Test {
  // prepare your sslContext and engine Provider
  implicit lazy val engineProvider = ClientSSLEngineProvider(engine => engine)

  implicit lazy val sslContext: SSLContext = {
    val context = SSLContext.getInstance("TLS")
    context.init(null, Array[TrustManager](new DummyTrustManager), new SecureRandom)
    context
  }

  private class DummyTrustManager extends X509TrustManager {

    def isClientTrusted(cert: Array[X509Certificate]): Boolean = true

    def isServerTrusted(cert: Array[X509Certificate]): Boolean = true

    override def getAcceptedIssuers: Array[X509Certificate] = Array.empty

    override def checkClientTrusted(x509Certificates: Array[X509Certificate], s: String): Unit = {}

    override def checkServerTrusted(x509Certificates: Array[X509Certificate], s: String): Unit = {}
  }

  // rewrite sendReceiveMethod fron spray.client.pipelining
  def mySendReceive(implicit refFactory: ActorRefFactory, executionContext: ExecutionContext,
                    futureTimeout: Timeout = 60.seconds): SendReceive = {
    val transport =  IO(Http)(actorSystem)
    // HttpManager actually also accepts Msg (HttpRequest, HostConnectorSetup)
    request =>
      val uri = request.uri
      val setup = HostConnectorSetup(uri.authority.host.toString, uri.effectivePort, uri.scheme == "https")
      transport ? (request, setup) map {
        case x: HttpResponse          => x
        case x: HttpResponsePart      => sys.error("sendReceive doesn't support chunked responses, try sendTo instead")
        case x: Http.ConnectionClosed => sys.error("Connection closed before reception of response: " + x)
        case x                        => sys.error("Unexpected response from HTTP transport: " + x)
      }
  }

  // use mySendReceive instead spray.client.pipelining.sendReceive
}