如何实现Akka HTTP请求发布客户端标头授权

问题描述 投票:0回答:2

我正在尝试实现Akka http客户端以进行邮寄请求,其中授权将在邮递员的标头中给出。我无法授权,以下是我的代码

 def main(args: Array[String]) {

    implicit val system: ActorSystem = ActorSystem()
    implicit val materializer: ActorMaterializer = ActorMaterializer()
    implicit val executionContext: ExecutionContextExecutor = system.dispatcher
    val requestHeader = scala.collection.immutable.Seq(RawHeader("Authorization", "admin"))

    val requestHandler: HttpRequest => HttpResponse = {

      case HttpRequest(POST, Uri.Path("/GetTrackerData"), requestHeader, entity, _) =>
        val chunk = Unmarshal(entity).to[DeviceLocationData]

        val deviceLocationData = Await.result(chunk, 1.second)

        val responseArray = "Authorized"
        HttpResponse(entity = HttpEntity(ContentTypes.`application/json`, responseArray)
        )

      case r: HttpRequest =>
        println(r.uri.toString())
        r.discardEntityBytes() // important to drain incoming HTTP Entity stream
        HttpResponse(404, entity = "Unknown resource!")
    }

    val bindingFuture = Http().bindAndHandleSync(requestHandler, "0.0.0.0", 7070)
    println(s"iot engine api live at 0.0.0.0:7070")
    sys.addShutdownHook({
      println("ShutdownHook called")
      bindingFuture
        .flatMap(_.unbind()) // trigger unbinding from the port
        .onComplete(_ => system.terminate()) // and shutdown when done
    })

  }

无论邮递员给我什么价值。它满足请求。我正在跳过什么?

我的用例是显示的结果仅在授权后才显示

scala http akka akka-http
2个回答
2
投票

您正在HttpRequest上进行模式匹配。

您使用的requestHeader不是您先前指定的,而是HttpRequest本身的headers

一种解决方法可能是检查标题中的值:

case HttpRequest(HttpMethods.POST, Uri.Path("/GetTrackerData"), headers, entity, _) 
  if (headers.exists(h => h.name == "Authorization" && h.value ==  "admin"))  =>

0
投票

这里是一个问题:

  case HttpRequest(POST, Uri.Path("/GetTrackerData"), requestHeader, entity, _) =>

这与requestHeader的当前值不匹配,它将创建一个包含requestHeader的当前标题的新值HttpRequest。因此,此匹配项将不会检查标题的Authorization字段。您将必须手动执行此操作。

更一般而言,值得一看的是Akka HTTP中对Route的支持,这是一种更清洁,功能更强大的服务器实现方式。

© www.soinside.com 2019 - 2024. All rights reserved.