如何使用 vert.x 访问 OpenAPI 上的安全端点?

问题描述

我正在使用 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?

解决方法

您不能为客户端使用 RouterBuilderJWTAuthHandler 为您注入 auth 标头。恐怕这部分必须通过在请求上手动设置 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

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...