Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
955 views
in Technique[技术] by (71.8m points)

scala - Akka HTTP 2.0 to use SSL (HTTPS)

I am trying to add a self signed certificate to my configuration in order to make my web service to serve content over SSL but I had no luck.

Here is my current configuration

ssl {
  jksKeystore = "localhost.p12"
  password = "changeit"
}

Any ideas on what I'm misisng to be able to spin up an HTTPS server ?

My project is using akka 2.0 and scala

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

There are some tests in the akka code base that test the https functionality. They use the predefined http contexts defined in ExampleHttpContexts.

I have created a small repo that uses the keys from the akka repository (I hope they won't mind) and creates a minimal https server using a self-signed certificate here. Done as a repo instead of as a gist so you can just clone it to get started.

Here is the scala code:

package httpsserver

import java.security.{SecureRandom, KeyStore}
import javax.net.ssl.{KeyManagerFactory, SSLContext}

import akka.actor.ActorSystem
import akka.http.scaladsl.{HttpsContext, Http}
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.Route
import akka.stream.ActorMaterializer

object Server extends App {

  val serverContext: HttpsContext = {
    val password = "abcdef".toCharArray
    val context = SSLContext.getInstance("TLS")
    val ks = KeyStore.getInstance("PKCS12")
    ks.load(getClass.getClassLoader.getResourceAsStream("keys/server.p12"), password)
    val keyManagerFactory = KeyManagerFactory.getInstance("SunX509")
    keyManagerFactory.init(ks, password)
    context.init(keyManagerFactory.getKeyManagers, null, new SecureRandom)
    // start up the web server
    HttpsContext(context)
  }

  implicit val system = ActorSystem("server")
  implicit val materializer = ActorMaterializer()
  import system._

  val route = Route(complete("ok"))

  Http().bindAndHandle(route, interface = "0.0.0.0", port = 8081, httpsContext = Some(serverContext))
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...