如何解决如何使用 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?
解决方法
您不能为客户端使用 RouterBuilder
和 JWTAuthHandler
为您注入 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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。