安全性未从 Open API 生成器添加到 Swagger

D. *_*scu 6 swagger spring-boot openapi openapi-generator

我正在团队中开发一个新项目,我们正在遵循 API 优先方法来实现 API。我们使用openapi-generator-maven-pluginOpenAPI 3.0.3 格式的 yml 文件生成 API。为了生成 swagger 文件,我们使用 springfox 2.9.2。我面临的问题是当我尝试为请求增加安全性时。

components:
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      bearerFormat: JWT
security:
  - bearerAuth: [ ]
Run Code Online (Sandbox Code Playgroud)

Authorize按钮不会出现在 swagger 页面中,仅出现请求附近的锁,但它不会执行任何操作(见下图)。

我观察到,如果我打开/v2/api-docsswagger json 不包含安全定义部分。

我设法添加安全性的唯一方法是通过 Docket 对象中的代码添加安全部分,如下所示:

new Docket(DocumentationType.SWAGGER_2)
    .securityContexts(Collections.singletonList(securityContext()))
    .securitySchemes(Collections.singletonList(bearerJwtKey()))
    .select()
    .apis(RequestHandlerSelectors.basePackage("com.example"))
    .paths(PathSelectors.any())
    .build();
Run Code Online (Sandbox Code Playgroud)

这是为 Swagger UI 添加安全性的唯一方法还是我遗漏了什么?

在此输入图像描述

xar*_*aiz 6

原因:Spring 库中尚未实现Bearer Auth :(

解决方案 - 扩展生成Docket

导入生成的配置类,然后将安全模式( ApiKey)添加到现有Docketbean。例子:

@Configuration
@Import(OpenAPIDocumentationConfig.class) // openapi generated config class
public class SwaggerConfiguration {
   @Autowired
   ApplicationContext context;

   @PostConstruct
   public void extendExistingDocketWithSecurity() {
      Docket docket = context.getBean(Docket.class);
      docker.securitySchemes(Collections.singletonList(bearer()));
   }

   private static ApiKey bearer() {
      // where "bearerAuth" - name of your schema in YML spec. file
      return new ApiKey ("bearerAuth", HttpHeaders.AUTHORIZATION, "header");
   }
Run Code Online (Sandbox Code Playgroud)

完毕!你真棒!现在您正在使用生成的 swagger 配置而不覆盖,而只是扩展