将Akka HTTP重定向到HTTPS [英] Redirect Akka HTTP to HTTPS

查看:85
本文介绍了将Akka HTTP重定向到HTTPS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当前,我有一个可同时用于HTTP和HTTPS的API,但是即使URL是使用HTTP调用的,我也需要将其仅路由到HTTPS.例如,两者都在工作:

Currently I have an API that works for both HTTP and HTTPS, but I need it to just route to HTTPS even if the URL is called using HTTP. For example, both are working:

http://app1_0.cloud.example.net/getSomething
https://app1_0.cloud.example.net/getSomething

Akka文档中有一些关于为证书添加 httpscontext 的内容,但是我不确定是否需要这样做,因为我已经在使用HTTPS.这就是它被称为的路线:

There is something in the Akka docs about adding httpscontext for certificates, but I'm not sure I need to do that because I already have HTTPS working. This is where the route it being called:

Http().bindAndHandle(aliveResponse〜路由,主机,端口)

host port application.conf 中定义.

有没有一种方法可以仅添加重定向或强制类型转换以确保将其发送到HTTPS?

Is there a way to just add a redirect or a cast to make sure it sent to HTTPS?

路线示例:

def marketsRoute = {
   pathPrefix("markets") {
     pathEnd{
       logRequestResult("Read markets", akka.event.Logging.InfoLevel) {
       get {
            implicit val timeout = Timeout(20, TimeUnit.SECONDS)

         val sitesResp = WaitListDAO.getMarkets
         complete(HttpResponse( entity = HttpEntity(MediaTypes.`application/json`, sitesResp.toJson.toString)))

         }
        }
      }
     }
    }
   }

要给出答案:

def marketsRoute = {
    scheme("http") {
      extract(_.request.uri) { uri =>
        redirect( uri.withScheme("https"),
          StatusCodes.MovedPermanently
        )
      }
    } ~
   pathPrefix("markets") {
     pathEnd{
       logRequestResult("Read a waitlist enable markets", akka.event.Logging.InfoLevel) {
       get {
            implicit val timeout = Timeout(20, TimeUnit.SECONDS)

         val sitesResp = WaitListDAO.getMarkets
         complete(HttpResponse( entity = HttpEntity(MediaTypes.`application/json`, sitesResp.toJson.toString)))

         }
        }
      }
     }
    }
   }

推荐答案

除非HTTPS服务器也在同一应用程序中 bindAndHandle -ed,否则不需要定义 HttpsConnectionContext.

Unless the HTTPS server is also being bindAndHandle-ed in the same app, you shouldn't need to define HttpsConnectionContext.

HTTPS重定向的路由(从相关的中提取博客帖子 )应如下所示:

The route for HTTPS redirect (extracted from this relevant blog post) should look something like below:

val route =
  scheme("http") {
    extract(_.request.uri) { uri =>
      redirect( uri.withScheme("https").withAuthority(hostName, portHttps),
        StatusCodes.MovedPermanently
      )
    }
  }

请注意,如果您使用的是标准HTTPS端口(即443),则不需要 .withAuthority().

Note that .withAuthority() is not needed if you’re using standard HTTPS port (i.e. 443).

这篇关于将Akka HTTP重定向到HTTPS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆