我正在尝试编写一个拒绝非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个问题:pass
为Directive0
& headerValueByName
为Directive1
,headerValueByName
为Directive1
& {{1是} ajax
。所以它不编译)
我的问题是:我可以以某种方式拥有本地范围的提取吗?如同,Directive0
不会逃避header
。
我知道我可以在不使用ajax
的情况下访问删除标题的请求,所以请不要回答。
答案 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
}
}
}
}