Search code examples
javaspringspring-bootswaggerswagger-ui

How to use Bearer or Apikey keywords automatically onswagger java


I am trying to make some security configurations in my SwaggerConfiguration class. My purpose is sending scheme keyword with authentication key like

curl -X GET "http://localhost:8080" -H "accept: */*" -H "Authorization: Bearer <authorization-value>"

or

curl -X GET "http://localhost:8080" -H "accept: */*" -H "Authorization: ApiKey <authorization-value>"

It is possible on ASP.NET Core but I can only achieve this in Java like this:

enter image description here

What shall I use for my Docket security scheme instead of ApiKey?

Docket docket = new Docket(DocumentationType.SWAGGER_2)
                    .select()
                    .apis(RequestHandlerSelectors.basePackage("mypackagename"))
                    .build()
                    .useDefaultResponseMessages(false)
                    .apiInfo(metaData())
                    .securitySchemes(Collections.singletonList(getApiKey()))
                    .securityContexts(Collections.singletonList(securityContext()));

private ApiKey getApiKey() {
    return new ApiKey("apiKey", "Authorization", "Header");
}

Solution

  • You can achieve this by Open API Specification 3. To do that you need to add a dependency:

    <dependency>
        <groupId>org.springdoc</groupId>
        <artifactId>springdoc-openapi-ui</artifactId>
        <version>${open.api.version}</version>
    </dependency>
    

    After including this you need to update the swagger configuration as and post that you do not need add Bearer scheme in front of your token:

    package com.test.config;
        
    import io.swagger.v3.oas.models.Components;
    import io.swagger.v3.oas.models.OpenAPI;
    import io.swagger.v3.oas.models.info.Info;
    import io.swagger.v3.oas.models.info.License;
    import io.swagger.v3.oas.models.security.SecurityRequirement;
    import io.swagger.v3.oas.models.security.SecurityScheme;
    import lombok.extern.log4j.Log4j2;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import springfox.documentation.builders.ApiInfoBuilder;
    import springfox.documentation.service.ApiInfo;
    import springfox.documentation.service.Contact;
    import springfox.documentation.swagger2.annotations.EnableSwagger2;
        
        @Configuration
        @EnableSwagger2
        @Log4j2
        public class SwaggerConfig {
            private static final String SCHEME_NAME = "bearerScheme";
            private static final String SCHEME = "Bearer";
            
            @Bean
            public OpenAPI customOpenAPI() {
                var openApi = new OpenAPI()
                        .info(getInfo());
        
                addSecurity(openApi);
        
                return openApi;
            }
    
            private Info getInfo() {
                return new Info()
                        .title("Your APIs Documentation")
                        .description("The API documentation for your Portal.")
                        .version("1.0.0")
                        .license(getLicense());
            }
        
            private License getLicense() {
                return new License()
                        .name("Your")
                        .url("https://www.yours.com/en/");
            }
            private void addSecurity(OpenAPI openApi) {
                var components = createComponents();
                var securityItem = new SecurityRequirement().addList(SCHEME_NAME);
        
                openApi
                        .components(components)
                        .addSecurityItem(securityItem);
            }
        
            private Components createComponents() {
                var components = new Components();
                components.addSecuritySchemes(SCHEME_NAME, createSecurityScheme());
        
                return components;
            }
        
            private SecurityScheme createSecurityScheme() {
                return new SecurityScheme()
                        .name(SCHEME_NAME)
                        .type(SecurityScheme.Type.HTTP)
                        .scheme(SCHEME);
            }
        
        } 
    

    For details you can refer this.