Akka-HTTP服务器支持https

  1. 首先先获取HTTPS的数字证书文件(官方的证书。。)
  2. 配置HTTPS实例,具体代码如下:
import java.io.InputStream
import java.security.{ SecureRandom, KeyStore }
import javax.net.ssl.{ SSLContext, TrustManagerFactory, KeyManagerFactory }

import akka.actor.ActorSystem
import akka.http.scaladsl.server.{ Route, Directives }
import akka.http.scaladsl.{ ConnectionContext, HttpsConnectionContext, Http }
import akka.stream.ActorMaterializer
import com.typesafe.sslconfig.akka.AkkaSSLConfig
implicit val system = ActorSystem()
implicit val mat = ActorMaterializer()
implicit val dispatcher = system.dispatcher

// Manual HTTPS configuration

val password: Array[Char] = "change me".toCharArray // do not store passwords in code, read them from somewhere safe!

val ks: KeyStore = KeyStore.getInstance("PKCS12")
val keystore: InputStream = getClass.getClassLoader.getResourceAsStream("server.p12")  
//数字证书是固定的p12文件格式 require(keystore
!= null, "Keystore required!") ks.load(keystore, password) val keyManagerFactory: KeyManagerFactory = KeyManagerFactory.getInstance("SunX509") keyManagerFactory.init(ks, password) val tmf: TrustManagerFactory = TrustManagerFactory.getInstance("SunX509") tmf.init(ks) val sslContext: SSLContext = SSLContext.getInstance("TLS") sslContext.init(keyManagerFactory.getKeyManagers, tmf.getTrustManagers, new SecureRandom) val https: HttpsConnectionContext = ConnectionContext.https(sslContext)

    3、但是不是什么官方的证书都可以的。有严格要求 

  • 对应的域名的证书(如*.a.com的证书不能应用到s.b.com的server服务器上。会造成证书错误的问题,与此站点不安全的结果,更甚至会导致数字证书泄露)
  • 严格的p12文档证书 

   4 、一个server服务器能够同时允许https和http,但是两种方法一起运行是因为是不能是同一个地址,会报错。

          一个server需要同时运行http和https的话就需要准备两个端口地址

       即单个应用程序中运行HTTP和HTTPS服务器,则可以调用bind...两次方法,一种用于HTTPS,另一种用于HTTP。

      具体代码如下:

上面的2的https的代码也要调用
// you can run both HTTP and HTTPS in the same application as follows:
val commonRoutes: Route = get { complete("Hello world!") }
Http().bindAndHandle(commonRoutes, "127.0.0.1", 443, connectionContext = https)
Http().bindAndHandle(commonRoutes, "127.0.0.1", 80)

猜你喜欢

转载自www.cnblogs.com/0205gt/p/12719408.html