DEV Community

Cover image for Global Header in Swagger-Ui Spring-Boot
Suraj
Suraj

Posted on • Edited on

Global Header in Swagger-Ui Spring-Boot

This article is about adding custom headers in all Apis globally without writing in each API method.

Why do we need it?

There are cases where we need some header value from consumers to validate the request.

Example - Basic-Auth-Token, which can be validated from a servlet filter, so we don’t need to add it as a header parameter in each API method.

But, on exposing the API, we would want that the Basic-Auth-Token parameter reflects in each API under Swagger-UI to make testing easier.

Like in below image

So, let's get on how to do it
  • The first step would be to create a docket bean as below


  @Bean
  public Docket docket() {
    return new Docket(DocumentationType.SWAGGER_2)
        .forCodeGeneration(true)
        .globalOperationParameters(globalParameterList()) 
// ^ here we are passing the global paramters to inlcude in swagger-ui
        .select()
        .apis( RequestHandlerSelectors.withClassAnnotation(RestController.class))
        .paths(PathSelectors.any())
        .build();
  }


Enter fullscreen mode Exit fullscreen mode
Make sure that @EnableSwagger2 is added in the Application file
  • Now, let's add global parameters that we need to pass in above docket bean


  private List<Parameter> globalParameterList() {

    val authTokenHeader =
        new ParameterBuilder()
            .name("AUTH-TOKEN") // name of the header
            .modelRef(new ModelRef("string")) // data-type of the header
            .required(true) // required/optional
            .parameterType("header") // for query-param, this value can be 'query'
            .description("Basic Auth Token")
            .build();

    return Collections.singletonList(authTokenHeader);
  }


Enter fullscreen mode Exit fullscreen mode
  • Add a RequestFilter to log the incoming request header that we just added.


@Component
@Slf4j
public class RequestFilter implements Filter {

  @Override
  public void doFilter(
      ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
      throws IOException, ServletException {
    log.info(
        "Value of AUTH-TOKEN  -> {}",
        ((HttpServletRequest) servletRequest).getHeader("AUTH-TOKEN"));
    filterChain.doFilter(servletRequest, servletResponse);
  }
}


Enter fullscreen mode Exit fullscreen mode
  • Finally, a simple hello-world controller to test what we just made.


@RestController
@RequestMapping("/hello-world")
public class HelloWorldController {

  @GetMapping
  public ResponseEntity sayHello() { // No header needed here - that got covered in docket
    return ResponseEntity.ok("Hello There!!!");
  }
}


Enter fullscreen mode Exit fullscreen mode
How the output will look like

Sample Project can be found at

GitHub logo s2agrahari / swagger-global-header-spring-boot

Global Header in Swagger without writing in Controller






If you enjoyed this story, please click the ❤️ button and share it to help others find it! Feel free to leave a comment below.

Read more: 👇

Grouping APIs in Swagger using springdoc-openapi

Top comments (1)

Collapse
 
c094728 profile image
c094728

This does not seem to work in springboot 2.6.4 with springfox 3.0
globalOperationParameter is deprecated and when I converted to use globalRequestParameter, the values show in the ui as required but if i click the send button with them empty they do not turn red and the busy spinner just spins without sending any request