Java 如何使用vert.x访问OpenAPI上的安全端点?
我正在使用vert.x-openAPI模块,我的petstore.yaml具有如下安全性:Java 如何使用vert.x访问OpenAPI上的安全端点?,java,openapi,vert.x,rest-assured,vert.x-webclient,Java,Openapi,Vert.x,Rest Assured,Vert.x Webclient,我正在使用vert.x-openAPI模块,我的petstore.yaml具有如下安全性: /pets/{petId}: get: summary: Info for a specific pet operationId: showPetById security: - ApiKeyAuth: [] 这是使用JWT身份验证处理程序在我的服务器端(Verticle)上操作ID的相关部分(我将从代码中输入JWT身份验证提供程序创建部分)
/pets/{petId}:
get:
summary: Info for a specific pet
operationId: showPetById
security:
- ApiKeyAuth: []
这是使用JWT身份验证处理程序在我的服务器端(Verticle)上操作ID的相关部分(我将从代码中输入JWT身份验证提供程序创建部分):
客户端不能使用
RouterBuilder
和JWTAuthHandler
为您注入auth头。恐怕这部分工作必须通过在请求上手动设置auth头来完成。这通常是通过以下方式完成的(使用Vertex的WebClient):
WebClient
.create(vertx,…)//设置参数,以便此客户端可以访问您的API
.post(“/pets/pet123”)
.putHeader(“授权”、“持有人”+令牌)
//现在提出实际请求并使用结果
如何获得身份验证令牌取决于。在您的情况下,对于测试,您可能最好的选择是使用模拟身份验证服务(而不是真正的keydepot)。您需要配置服务器,以使用模拟身份验证,而不是仅用于测试(使用配置)的真正密钥斗篷,对于客户端,在测试中,只需从中获取令牌
这个模拟身份验证服务就是一个有效的例子:为什么在测试中使用
RouterBuilder
?一个应该在服务器端用于加载OpenAPI规范和装载处理程序,它对客户端没有任何作用。此外,您的代码缺少很多片段,问题可能在任何地方,从未正确配置的客户端到为JWT auth设置了错误/错误密钥的服务器……ok@mohamnag您能举一些简单的例子说明如何做这件事的好方法吗?谢谢对于客户端,您实际上不能使用任何库来神奇地为您设置安全性。OAuth很清楚,您需要用户交互才能获得令牌。对于测试,我将设置一个模拟OAuth服务器,它在没有交互的情况下为您提供令牌,并更改服务器代码,以便它连接到该模拟服务器。例如,使用config values.ok,我想我已经很清楚如何在安全端点上生成令牌,另一方面,关于使用config values的模拟oAuth服务器,您有一些有用的链接或示例吗?非常感谢mohamnag。
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?