我有一个使用Java EE 8编写的应用程序,在其中使用OpenAPI注解来定义我的REST端点,并自动生成Swagger UI。我使用JSON Web Tokens (JWT)进行身份验证。
当我从Postman发送请求时,一切都正常,但是我不知道如何在我的Swagger UI中添加用于bearer token的字段。
我使用@SecurityScheme
注解定义了安全方案:
@SecurityScheme(
securitySchemeName = "JWT",
description = "JWT authentication with bearer token",
type = SecuritySchemeType.HTTP,
scheme = "bearer",
bearerFormat = "Bearer [token]"
)
public class ApplicationConfig extends Application {
}
我已尝试将此方案添加为我的资源的@OpenAPIDefinition
注解和直接添加到我的方法中的@SecurityRequirement
。
@Path("/items")
@OpenAPIDefinition(
info = @Info(title = "Items resource", version = "v1"),
security = @SecurityRequirement(name = "JWT")
)
@Transactional(value = TxType.REQUIRES_NEW)
@Interceptors({RolesAllowedInterceptor.class})
@SecurityScheme(
securitySchemeName = "JWT",
description = "JWT authentication with bearer token",
type = SecuritySchemeType.HTTP,
scheme = "bearer",
bearerFormat = "Bearer [token]"
)
public class ItemsResource {
(...)
@GET
@Operation(description = "Returns the item list overview")
@APIResponse(responseCode = "200", description = "Valid response")
@APIResponse(responseCode = "401", description = "Authentication required")
@APIResponse(responseCode = "500", description = "Unexpected exception")
@Produces({MediaType.APPLICATION_JSON})
@SecurityRequirement(name ="JWT", scopes = "write: read")
@RolesAllowed({Constants.USER_ROLE_EXPERT})
public Response getItemListOverview() throws TechnicalException {
ItemListOverviewVO itemListOverviewVO = logic.getItemListOverview();
return Response.status(Status.OK).entity(itemListOverviewVO).build();
}
现在,在我的OpenAPI JSON文件中,我有了关于安全性
的信息,但是UI中仍然没有授权参数的字段。
我还发现旧版Swagger API中有一个@ApiImplicitParameter
注释(参见Swagger UI传递身份验证令牌到头部的API调用),但似乎已从OpenAPI中删除。
因此,我尝试使用@HeaderParam
替代它(参见Jersey项目Swagger-UI不发送@HeaderParam而发送@PathParam):
public Response getItemListOverview(@HeaderParam("Authorization") String bearerToken) throws TechnicalException {
现在我的UI界面中有一个“授权”字段,但是当我测试端点时,请求中没有任何授权头。我不能在浏览器的网络分析中看到它。
迄今为止,OpenAPI文档并没有提供太多帮助。我是否漏掉了什么?
@OpenAPIDefinition
似乎是SwaggerUI的一部分,具体来说是swagger-annotations
包中的内容。可以通过谷歌搜索轻松找到它。 - stefanS@OpenAPIDefinition
似乎是SwaggerUI的一部分,具体是在swagger-annotations
包中。通过谷歌搜索很容易找到。 - undefined