Security is not added to Swagger from Open API generator

Viewed 1398

I am working on a new project in my team and we are implementing an API following the API first methodology. We are using openapi-generator-maven-plugin to generate our API from an yml file of format OpenAPI 3.0.3. To generate the swagger file we use springfox 2.9.2. The issue that I am facing is when I am trying to add security to the swagger for the requests.

components:
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      bearerFormat: JWT
security:
  - bearerAuth: [ ]

The Authorize button doesn't appear in swagger page, only the lock near to the request appears but it doesn't do anything (see picture below).

What I observed is that if I open the /v2/api-docs the swagger json doesn't include the security definitions part.

The only way that I managed to add security is by adding by code in the Docket object the security part like so:

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

Is this the only way to add security to Swagger UI or am I missing something?

enter image description here

1 Answers

Reason: Bearer Auth isn't implemented in spring library yet :(

Workaround solution - extend generated Docket:

Import generated config class and then add a security schema (ApiKey) to the existing Docket bean. Example:

@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");
   }

Done! You're awesome! Now you're using generated swagger config without overriding, but just extending

Related