Global Header in Swagger-Ui Spring-Boot
Tags: swagger, springboot, header, globaloperationparameters
Published: 2020-05-23 11:49:02

![](https://github.com/s2agrahari/img-dump/blob/master/globalOperationParameters.png?raw=true)

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

![](https://github.com/s2agrahari/img-dump/blob/master/global-header-swagger-ui.png?raw=true)

#####So, let's get on how to do it#####

* The first step would be to create a docket bean as below

```java
  @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();
  }
```

###### 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

```java
  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);
  }
```

* Add a RequestFilter to log the incoming request header that we just added.

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

* Finally, a simple hello-world controller to test what we just made.

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

##### How the output will look like
![](https://github.com/s2agrahari/img-dump/blob/master/passing-auth-token-in-swagger-ui.png?raw=true)

![](https://github.com/s2agrahari/img-dump/blob/master/dummy-auth-token-in-swagger-ui-log.png?raw=true)

Sample Project can be found at {% github https://github.com/s2agrahari/swagger-global-header-spring-boot %}

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

Read more: :point_down:

[Grouping APIs in Swagger using springdoc-openapi](
https://dev.to/s2agrahari/grouping-apis-in-swagger-55kk)