0

我正在使用 vert.x-openAPI 模块,并且我的 petstore.yaml 具有以下安全性:

/pets/{petId}:
    get:
      summary: Info for a specific pet
      operationId: showPetById
      security:
        - ApiKeyAuth: []

这是我的服务器端(Verticle)上使用 JWT Auth Handler 的 operationId 的相关部分(我将在我的代码中省略 JWT Auth 提供程序创建部分):

 routerBuilder.setOptions(routerBuilderOptions)
      .securityHandler("ApiKeyAuth", JWTAuthHandler.create(jwtAuthProvider))
      .operation("showPetById")
      .handler(routingContext -> {
        RequestParameters params = routingContext.get(ValidationHandler.REQUEST_CONTEXT_KEY);
        Integer id = params.pathParameter("petId").getInteger();
        Optional<JsonObject> pet = getAllPets()
          .stream()
          .filter(p -> p.getInteger("id").equals(id))
          .findFirst();
        if(pet.isPresent()){
          routingContext
            .response()
            .setStatusCode(200)
            .putHeader(HttpHeaders.CONTENT_TYPE,"application/json")
            .end(pet.get().encode());
        }else {
          routingContext.fail(404, new Exception("Pet not found"));
        }

      });

然后,我尝试从我的测试访问该端点并获得成功(并且授权正常)响应:

@Test
  public void breakingTheAuth(Vertx vertx, VertxTestContext vertxTestContext){

    Checkpoint checkFlag = vertxTestContext.checkpoint(2);
    //Checkpoint jwtCheck = vertxTestContext.checkpoint();
    vertxTestContext.verify(()->{
      JWTAuth jwt = loadJWTAuthprovider(vertx);
      checkFlag.flag();
      RouterBuilder.create(vertx,"petstore.yaml")
        .onSuccess(routerBuilder -> {
          routerBuilder.setOptions(FACTORY_OPTIONS)
            .securityHandler("ApiKeyAuth", JWTAuthHandler.create(jwt))
            .operation("showPetById")
            .handler(routingContext -> {
              given()
                .port(8080)
                .get("/pets/2")
                .then()
                .statusCode(200);

            });
          checkFlag.flag();
        }).onFailure(throwable -> {
          vertxTestContext.failNow(throwable);
        });
    });
  }


    I would like to access to this endpoint http://localhost:8080/pets/2 with a 200 status code as a response but I always get the 401 Unauthorized (Maybe a JWTAuth problem, I've read about using oAUTH it could be a better option).
    Maybe I am missing anything, should I use the vertx-webclient to access to that endpoint?
4

1 回答 1

1

您不能使用RouterBuilderandJWTAuthHandler让客户端为您注入 auth 标头。恐怕这部分必须通过手动设置请求的身份验证标头来完成。这通常以这样的方式完成(使用 Vertx 的 WebClient):

WebClient
      .create(vertx, ...) // set params so that this client can reach your API
      .post("/pets/pet123")
      .putHeader("authorization", "Bearer " + token)
      // now make the actual request and use the results

您如何获得身份验证令牌取决于。在您的情况下,对于测试,您可能最好的选择是使用模拟身份验证服务(而不是真正的 Keycloak)。您需要将服务器配置为仅使用模拟身份验证而不是真正的 Keycloak 进行测试(使用配置),对于客户端,在您的测试中只需从中获取令牌。

此模拟身份验证服务是可行的示例:https ://github.com/TNG/keycloak-mock

于 2021-05-09T09:22:48.273 回答