如何在akka http中对路由标头中的OAuth2BearerToken进行单元测试

liwlm1x9  于 2022-11-06  发布在  其他
关注(0)|答案(1)|浏览(132)

我有一个路由,它需要一个访问令牌在它的头部,以授予它的访问权,我有这个工作代码

def accessProtectedResource: server.Route =
    path("access-protected-resource") {
      get {
        bearerToken { token =>
          token match {
            case Some(tokenValue) =>
              complete(OK, routeResponseMessage.getResponse(OK.intValue,ServerMessages.AUTH_PASS,JsObject.empty))
            case None => reject(AuthorizationFailedRejection)
          }
        }
      }
    }

  private def bearerToken: Directive1[Option[String]] =
    for {
      authBearerHeader <- optionalHeaderValueByType(classOf[Authorization]).map(extractBearerToken)
      xAuthCookie <- optionalCookie("X-Authorization-Token").map(_.map(_.value))
    } yield authBearerHeader.orElse(xAuthCookie)

  private def extractBearerToken(authHeader: Option[Authorization]): Option[String] =
    authHeader.collect {
      case Authorization(OAuth2BearerToken(token)) => token
    }

当我在Authorization选项卡中点击通过 Postman 的路由时,我选择了Bearer Token的类型,并添加了令牌,发送了请求,现在一切都正常,我想对此路由进行单元测试,我正在查看this
但是我很困惑,我怎么能在我的单元测试中以正确的方式添加头呢?

"pass route /access-protected-resource" in {
    routeResponseMessage.getResponse(OK.intValue, ServerMessages.AUTH_PASS, JsObject.empty)

val originHeader = Authorization(OAuth2BearerToken("accessTokenString"))

    Get("http://0.0.0.0:8083/get-user-token") ~> originHeader ~> authenticationController.route ~> check {

    }

  }

但我的路线被拒绝了

- pass route /access-protected-resource***FAILED***
[info]   Request was rejected with rejection MethodRejection(HttpMethod(POST)) (CheckValidUserTokenExistsTest.scala:76)

如何正确地做到这一点?

tpxzln5u

tpxzln5u1#

使用addCredential并只测试用Route.seal Package 的bearerToken方法怎么样?

相关问题