Search code examples
spring-bootswagger-uiswagger-3.0

Swagger 3 Required Global Request Parameter


I am using Spring Boot 2.5.4 with Swagger 3. I have added one Global Request Parameter as type header and required=true in Swagger Config file . Swagger UI is correctly showing the required request header in all APIs but the problem is that it's allowing requests to be sent when the value is empty for required request header. In Swagger 2 , UI used to disable sending request until the value was filled.

Any suggestions.

@Bean
    public Docket api() {

        RequestParameterBuilder aParameterBuilder = new RequestParameterBuilder();
        aParameterBuilder.name("x-remote-user").description("Remote User").in(ParameterType.HEADER).required(true)
                .build();

        List<RequestParameter> aParameters = new ArrayList<>();
        aParameters.add(aParameterBuilder.build());
        return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo())
                .securityContexts(Arrays.asList(securityContext())).securitySchemes(Arrays.asList(apiKey())).select()
                .apis(RequestHandlerSelectors.basePackage("com.xxx.controller"))
                .paths(PathSelectors.ant("/api/**")).build().globalRequestParameters(aParameters);
    }

Solution

  • I found out the solution . Posting it here if someone else is looking for it .

    If we disallow empty values , then swagger UI starts blocking us from Executing API if header value is kept empty.

    @Bean
        public Docket api() {
    
            return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo())
                    .securityContexts(Arrays.asList(securityContext())).securitySchemes(Arrays.asList(apiKey())).select()
                    .apis(RequestHandlerSelectors.basePackage("com.xxx.controller"))
                    .paths(PathSelectors.ant("/api/**")).build()
                    .globalRequestParameters(Arrays.asList(new RequestParameterBuilder().name("x-remote-user")
                            .description("Remote User").in(ParameterType.HEADER).required(true)
                            .query(simpleParameterSpecificationBuilder -> simpleParameterSpecificationBuilder
                                    .allowEmptyValue(false).model(modelSpecificationBuilder -> modelSpecificationBuilder
                                            .scalarModel(ScalarType.STRING)))
                            .build()));
        }