简体   繁体   English

如何在Akka HTTP指令中使用Future?

[英]How can I use a Future inside an Akka HTTP Directive?

I currently have a directive that I'm using to secure resources in an Akka HTTP app, like so: 我目前有一个指令,我用来保护Akka HTTP应用程序中的资源,如下所示:

def authenticate: Directive1[Login] =
  optionalHeaderValueByName("Authorization") flatMap {
    val accessToken = authz.split(' ').last
    case Some(authz) =>
      LoggedInUser findByAccessToken accessToken match {
        case Some(user) => provide(user)
        case None       => reject(AuthorizationFailedRejection)
      }
    case None => reject(AuthorizationFailedRejection)
  }

where LoggedInUser.findByAccessToken() makes a blocking query against a database, I would like to switch this for an asynchronous ask to an actor which which can provide the same data, I'm OK with passing in the ActorRef as a parameter to the directive but I cannot work out how to handle the Future that the ask returns. 其中LoggedInUser.findByAccessToken()对数据库进行阻塞查询,我想将此切换为异步ask给可以提供相同数据的actor,我可以将ActorRef作为参数传递给指令但我无法弄清楚如何处理问题返回的Future

None of the Directive1 examples that come with Akka HTTP seem to do this (at least I could;t find any) although there are examples of directives returning Route which do. Akka HTTP附带的Directive1示例似乎都没有这样做(至少我可以找到),尽管有返回Route的指令的例子。

Is what I want to do even possible? 我甚至想做什么? Is a possible approach to create a StandardRoute subclass with a field for the user credentials and return that somehow? 是一种可能的方法来创建一个StandardRoute子类与一个用户凭据的字段,并以某种方式返回?

Yes, it is possible. 对的,这是可能的。 As far as I understand you need something like this: 据我所知,你需要这样的东西:

def authenticate: Directive1[Login] = {
  def findByAccessToken(accessToken:String): Future[Option[Login]] = ???
  optionalHeaderValueByName("Authorization").flatMap {
    case Some(authz) =>
      val accessToken = authz.split(' ').last
      onSuccess(findByAccessToken(accessToken)).flatMap {
        case Some(user) => provide(user)
        case None       => reject(AuthorizationFailedRejection)
      }
    case None => reject(AuthorizationFailedRejection)
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM