【问题标题】:scala akka http route with authenticate by a token通过令牌进行身份验证的scala akka http路由
【发布时间】:2016-12-19 16:21:57
【问题描述】:

我正在尝试在 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重写validateTokenApp()吗?

标签: scala akka akka-http


【解决方案1】:

看起来 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 =>
            ...
        }
      }
    }
  }

【讨论】:

  • 它运作良好,但你能解释一下“my_realm”是什么吗?
  • tools.ietf.org/html/rfc6750tools.ietf.org/html/rfc2617中描述的可选参数。在 Spray 中,您可以在使用 AuthenticationFailedRejection 拒绝时完全不指定任何挑战,而 Akka-HTTP 再次更加严格。请注意,领域是可选的,您也可以使用reject(AuthenticationFailedRejection(CredentialsMissing, HttpChallenge("OAuth2", None))): Directive1[T] 拒绝
  • realm 是一个字符串而不是一个 Option[String] 所以我认为你不能传递一个“无”
猜你喜欢
  • 2020-07-17
  • 2013-06-12
  • 1970-01-01
  • 1970-01-01
  • 2014-10-30
  • 2016-05-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多