2

Is there any way to change a http server to https using the library http4s? (https://http4s.org/)

1 Answers1

5

I found myself facing this same issue but I managed to solve it, here's the thing:

  1. You need to look for the moment when you build your server, presumably with BlazeServerBuilder.

  2. BlazeServerBuilder has the method "withSslContext(sslContext: SSLContext)" to enable SSL. Thus, all you need to do is create a SSLContext object and pass it to the server builder.

Remember that you will probably have to store your SSL certificate in a keystore using Java's keytool utility before using it.

SSL context and SSL certificate

How to create an SSL context with an SSL certificate is another question, but here is an interesting post that covers the process of getting a free certificate from Let's Encrypt, storing it in a keystore and using it from a Java application: Using Let's Encrypt certificates in Java applications - Ken Coenen — Ordina JWorks Tech Blog

And here's the code I used for creating a SSLContext in Scala:

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
Stephen Ostermiller
  • 23,933
  • 14
  • 88
  • 109
ulitol97
  • 66
  • 1
  • 4
  • example: https://github.com/http4s/http4s/blob/main/examples/src/main/scala/com/example/http4s/ssl.scala – Kevin Won Mar 05 '21 at 19:48
  • A tutorial to add Letsencrypt to a http4s project can be found here https://www.scalawilliam.com/letsencrypt-http4s/ – sentenza May 20 '22 at 08:18