1

我正在尝试编写一个拒绝非 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 个问题:passis Directive0& headerValueByNameisDirective1headerValueByNameis Directive1& ajaxis Directive0。所以它不能编译)

我的问题是:我能以某种方式获得本地范围的提取吗?如中,header不逃跑ajax


我知道我可以访问请求以将标头拉出,而无需使用headerValue*,因此请不要回答。

4

1 回答 1

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
      }
    }
  }
}
于 2016-08-03T08:11:01.723 回答