为什么授权指令在应该保护的代码之后执行? [英] Why does authorize directive execute after the code it's supposed to protect?

查看:66
本文介绍了为什么授权指令在应该保护的代码之后执行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用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 方法。

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.

如文档中所述

http://spray.io/documentation/1.2.2/spray-routing/advanced-topics/understanding-dsl-structure/#understanding-extractions

正确的方式是这样的:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆