为什么授权指令在应该保护的代码之后执行? [英] Why does authorize directive execute after the code it's supposed to protect?
问题描述
我正在使用Scala 2.11.2,Akka 2.3.6和Spray 1.3.2。
I am using Scala 2.11.2, Akka 2.3.6 and Spray 1.3.2.
我遇到了的问题授权
指令。这是代码中有趣的部分:
I'm facing an issue with the authorize
directive. Here is the interesting part of the code:
val authenticatorActor = context.actorOf(Props[AuthenticatorActor])
implicit val timeout = Timeout(5 seconds)
cookie("userName") { cookie =>
def optionUser = Await.result(authenticatorActor ? cookie.content, timeout.duration).asInstanceOf[Option[User]]
authorize(isAuthorized(optionUser)) { // ?????
val user = optionUser.get
//do stuff
}
}
def isAuthorized(user: Option[User]): Boolean =
user match {
case Some[User] => true
case None => false
}
基本上,我检查cookie以验证用户凭据。
Basically, I check the cookie to validate the user credentials.
问题是 authorize
指令中的块在 isAuthorize $ c之前执行$ c>方法。
The problem is that the block inside the authorize
directive is executed before the isAuthorize
method.
因此,如果将来返回 None
,则代码在中失败val user = optionUser.get
带有难看的 NonSuchElementException
。
So if the future returns a None
, code fails in val user = optionUser.get
with an ugly NonSuchElementException
.
如果 authorize
指令由如果
语句(如下面的代码段中的所有语句都可以正常运行)更改:
If the authorize
directive is changed by an if
statement like in the snippet below all work fine:
if (isAuthorized(optionUser)) {
//do stuff
} else reject(ValidationRejection("User has not access"))
有什么想法吗?
更新
我正在添加 // do东西
块作为参考
get {
path("") {
complete {
s"Hi ${user.name}. You have the next access: ${user.acceso}.\nWelcome to the ping-pong match"
}
} ~
path("ping") {
complete("pong")
} ~
path("pong") {
complete ("ping")
}
}
推荐答案
感谢Gangstead和user3567830的答复。
Thanks to Gangstead and user3567830 for the answere.
如文档中所述
正确的方式是这样的:
authorize(isAuthorize(optionUser)) {
get {
path("") {
complete {
val user = optionUser.get
s"Hi ${user.name}. You have the next access: ${user.acceso}.\nWellcome to the ping-pong match"
}
}
}
....
这篇关于为什么授权指令在应该保护的代码之后执行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!