akka-http:如何使用/隐藏提取的值?

时间:2016-08-03 07:41:11

标签: akka-http spray-routing

我正在尝试编写一个拒绝非ajax请求的指令。下面的代码显然不起作用:

import akka.http.scaladsl.model.HttpHeader
import akka.http.scaladsl.server.Directive0
import akka.http.scaladsl.server.directives.BasicDirectives
import akka.http.scaladsl.server.directives.HeaderDirectives
import akka.http.scaladsl.server.directives.RouteDirectives

trait AjaxDirectives extends BasicDirectives with HeaderDirectives with RouteDirectives {
  private val valid = "XMLHttpRequest"

  def ajax(): Directive0 = {
    headerValueByName("X-Requested-With") { header ⇒
      if (header == valid) {
        pass
      } else {
        reject
      }
    }
  }
}

(此处有2个问题:passDirective0& headerValueByNameDirective1headerValueByNameDirective1& {{1是} ajax。所以它不编译)

我的问题是:我可以以某种方式拥有本地范围的提取吗?如同,Directive0不会逃避header

我知道我可以在不使用ajax的情况下访问删除标题的请求,所以请不要回答。

1 个答案:

答案 0 :(得分:1)

阅读SecurityDirectives.authorizeAsync给了我答案:

import akka.http.scaladsl.model.HttpHeader
import akka.http.scaladsl.server.Directive0
import akka.http.scaladsl.server.directives.BasicDirectives
import akka.http.scaladsl.server.directives.HeaderDirectives
import akka.http.scaladsl.server.directives.RouteDirectives

trait AjaxDirectives extends BasicDirectives with HeaderDirectives with RouteDirectives {
  private val headerName = "X-Requested-With"
  private val valid = "XMLHttpRequest"

  def ajax(): Directive0 = {
    headerValueByName(headerName).flatMap { header ⇒
      if (header == valid) {
        pass
      } else {
        reject
      }
    }
  }
}