通过令牌进行身份验证的 scala akka http 路由

scala akka http route with authenticate by a token

我正在尝试在 akka http 中转换我的喷雾路线。

对于新手来说真的很复杂,但我几乎什么都会。 我被身份验证搞糊涂了。

确实,我有一个带有 get param token=????? 我怎样才能用akka检查这个令牌? 我的路线是:

  val route : Route = {
    path("appActive") {
            get {
                parameters('date_end.as[Long]) {
                    date_end =>
                        onSuccess(requestHandler ? AppActiveGetList(AppActiveRequest(date_end, null, 0))) {
                            case response: Answer =>
                                complete(StatusCodes.OK, response.result)
                            case _ =>
                                complete(StatusCodes.InternalServerError, "Error on the page")
                        }
                }
        }
    }
}

我目前的身份验证功能是(带喷雾):

trait TokenValidator {
def validateTokenApp(): ContextAuthenticator[InfoApp] = {
    ctx =>
        val access_token = ctx.request.uri.query.get("access_token")
        if (access_token.isDefined) {
            doAuthApp(access_token.get)
        } else {
            Future(Left(AuthenticationFailedRejection(AuthenticationFailedRejection.CredentialsMissing, List())))
        }
}
}

我没有找到可以轻松使用的示例。 你能帮帮我吗?

看起来 Akka-HTTP 身份验证指令在他们期望的方面比 Spray 的更严格。 如果你想保持你的 doAuthApp 不变,你需要定义你自己的自定义指令 - 按照 Akka-HTTP 自己的 authenticateOrRejectWithChallenge.

  def doAuthApp[T](token: String): Future[AuthenticationResult[T]] = ???

  def authenticated[T](authenticator: String => Future[AuthenticationResult[T]]): AuthenticationDirective[T] =
    parameter('access_token.?).flatMap {
      case Some(token) =>
        onSuccess(authenticator(token)).flatMap {
          case Right(s) => provide(s)
          case Left(challenge) =>
            reject(AuthenticationFailedRejection(CredentialsRejected, challenge)): Directive1[T]
        }
      case None =>
        reject(AuthenticationFailedRejection(CredentialsMissing, HttpChallenges.oAuth2("my_realm"))): Directive1[T]
    }

然后在某处布线,例如

  val route : Route = {
    path("appActive") {
      (get & authenticated(doAuthApp)){ authResult =>
        parameters('date_end.as[Long]) {
          date_end =>
            ...
        }
      }
    }
  }