使用 http4s 从 http 更改为 https

Change from http to https using http4s

有没有办法使用库 http4s 将 http 服务器更改为 https? (https://http4s.org/)

我发现自己也遇到了同样的问题,但我设法解决了,事情是这样的:

  1. 您需要在构建服务器时寻找时机,大概是使用 BlazeServerBuilder。

  2. BlazeServerBuilder 有方法“withSslContext(sslContext: SSLContext)”来启用 SSL。因此,您需要做的就是创建一个 SSLContext 对象并将其传递给服务器构建器。

请记住,在使用之前,您可能必须使用 Java 的 keytool 实用程序将 SSL 证书存储在密钥库中。

SSL 上下文和 SSL 证书

如何使用 SSL 证书创建 SSL 上下文是另一个问题,但这里有一个有趣的 post 涵盖了从 Let's Encrypt 获取免费证书、将其存储在密钥库中并使用它的过程来自 Java 应用程序:Using Let's Encrypt certificates in Java applications - Ken Coenen — Ordina JWorks Tech Blog

下面是我用于在 Scala 中创建 SSLContext 的代码:

val keyStorePassword: String   = your_keystore_password
val keyManagerPassword: String = your_certificate_password
val keyStorePath: String       = your_keystore_location

val keyStore = KeyStore.getInstance(KeyStore.getDefaultType)

val in = new FileInputStream(keyStorePath)
keyStore.load(in, keyStorePassword.toCharArray)

val keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm)
keyManagerFactory.init(keyStore, keyStorePassword.toCharArray)

val trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm)
trustManagerFactory.init(keyStore)

val sslContext = SSLContext.getInstance("TLS")
sslContext.init(keyManagerFactory.getKeyManagers, trustManagerFactory.getTrustManagers, new SecureRandom())
sslContext