httphttpshttp4s

Change from http to https using http4s


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


Solution

  • 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