我想将http请求发布到具有给定ca证书的安全服务器。
我正在使用Spray 1.3.1,代码看起来像这样:
val is = this.getClass().getResourceAsStream("/cacert.crt")
val cf: CertificateFactory = CertificateFactory.getInstance("X.509")
val caCert: X509Certificate = cf.generateCertificate(is).asInstanceOf[X509Certificate];
val tmf: TrustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
val ks: KeyStore = KeyStore.getInstance(KeyStore.getDefaultType());
ks.load(null);
ks.setCertificateEntry("caCert", caCert);
tmf.init(ks);
implicit val sslContext: SSLContext = SSLContext.getInstance("TLS");
sslContext.init(null, tmf.getTrustManagers(), null);
implicit val timeout: Timeout = Timeout(15.seconds)
import spray.httpx.RequestBuilding._
val respFuture = (IO(Http) ? Post( uri=Uri(url), content="my content")).mapTo[HttpResponse]
问题是没有采用定义的隐式SSLContext,我得到:“无法在运行时找到有效的证书路径”。
如何定义与喷雾客户端一起使用的SSLContext?
答案 0 :(得分:2)
我使用以下命令在spray中定义SSLContext。就我而言,我使用的是非常宽松的上下文,不会验证远程服务器的证书。基于this post中的第一个解决方案 - 对我有用。
import java.security.SecureRandom
import java.security.cert.X509Certificate
import javax.net.ssl.{SSLContext, X509TrustManager, TrustManager}
import akka.actor.ActorRef
import akka.io.IO
import akka.util.Timeout
import spray.can.Http
import scala.concurrent.Future
trait HttpClient {
/** For the HostConnectorSetup ask operation. */
implicit val ImplicitPoolSetupTimeout: Timeout = 30 seconds
val hostName: String
val hostPort: Int
implicit val sslContext = {
/** Create a trust manager that does not validate certificate chains. */
val permissiveTrustManager: TrustManager = new X509TrustManager() {
override def checkClientTrusted(chain: Array[X509Certificate], authType: String): Unit = {
}
override def checkServerTrusted(chain: Array[X509Certificate], authType: String): Unit = {
}
override def getAcceptedIssuers(): Array[X509Certificate] = {
null
}
}
val initTrustManagers = Array(permissiveTrustManager)
val ctx = SSLContext.getInstance("TLS")
ctx.init(null, initTrustManagers, new SecureRandom())
ctx
}
def initClientPool(): Future[ActorRef] = {
val hostPoolFuture = for {
Http.HostConnectorInfo(connector, _) <- IO(Http) ? Http.HostConnectorSetup(hostName, port = hostPort,
sslEncryption = true)
} yield connector
}
}
答案 1 :(得分:0)
我想出了sendReceive
的替代品,允许传递自定义SSLContext
(作为implicit
)
def mySendReceive( request: HttpRequest )( implicit uri: spray.http.Uri, ec: ExecutionContext, futureTimeout: Timeout = 60.seconds, sslContext: SSLContext = SSLContext.getDefault): Future[ HttpResponse ] = {
implicit val clientSSLEngineProvider = ClientSSLEngineProvider { _ =>
val engine = sslContext.createSSLEngine( )
engine.setUseClientMode( true )
engine
}
for {
Http.HostConnectorInfo( connector, _ ) <- IO( Http ) ? Http.HostConnectorSetup( uri.authority.host.address, port = uri.authority.port, sslEncryption = true )
response <- connector ? request
} yield response match {
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 )
}
}
然后将其用作&#34;通常&#34; (几乎见下文):
val pipeline: HttpRequest => Future[ HttpResponse ] = mySendReceive
pipeline( Get( uri ) ) map processResponse
我真的有几件事情不喜欢:
这是一个黑客攻击。我希望spray-client
能够原生地支持自定义SSLContext
。这些在开发和测试期间非常有用,通常强制自定义TrustManagers
有一个implicit uri: spray.http.Uri
参数可以避免连接器上主机和端口的硬编码。因此uri
必须声明为implicit
。
对此代码的任何改进,甚至更好,spray-client
的补丁,都是最受欢迎的(SSLEngine创建的外部化是显而易见的)
答案 2 :(得分:0)
我开始工作的最短时间是:
IO(Http) ! HostConnectorSetup(host = Conf.base.getHost, port = 443, sslEncryption = true)
即。 @ reed-sandberg的回答是什么,但似乎不需要问问模式。我没有将连接参数传递给sendReceive
,而是:
// `host` is the host part of the service
//
def addHost = { req: HttpRequest => req.withEffectiveUri(true, Host(host, 443)) }
val pipeline: HttpRequest => Future[Seq[PartitionInfo]] = (
addHost
~> sendReceive
~> unmarshal[...]
)
这似乎有效,但我很自然会想知道这种方法是否有缺点。
我同意所有喷涂客户端SSL支持批评。像这样的事情是如此艰难,这很尴尬。我可能花了两天时间来合并来自不同来源的数据(SO,喷雾文档,邮件列表)。