Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

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 addingcustom 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
@BeanpublicDocketdocket(){returnnewDocket(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 modeExit 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
privateList<Parameter>globalParameterList(){valauthTokenHeader=newParameterBuilder().name("AUTH-TOKEN")// name of the header.modelRef(newModelRef("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();returnCollections.singletonList(authTokenHeader);}
Enter fullscreen modeExit fullscreen mode
  • Add a RequestFilter to log the incoming request header that we just added.
@Component@Slf4jpublicclassRequestFilterimplementsFilter{@OverridepublicvoiddoFilter(ServletRequestservletRequest,ServletResponseservletResponse,FilterChainfilterChain)throwsIOException,ServletException{log.info("Value of AUTH-TOKEN  -> {}",((HttpServletRequest)servletRequest).getHeader("AUTH-TOKEN"));filterChain.doFilter(servletRequest,servletResponse);}}
Enter fullscreen modeExit fullscreen mode
  • Finally, a simple hello-world controller to test what we just made.
@RestController@RequestMapping("/hello-world")publicclassHelloWorldController{@GetMappingpublicResponseEntitysayHello(){// No header needed here - that got covered in docketreturnResponseEntity.ok("Hello There!!!");}}
Enter fullscreen modeExit fullscreen mode
How the output will look like

Sample Project can be found at


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)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss
CollapseExpand
 
c094728 profile image
c094728
  • Joined

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

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Happy to Develop
  • Joined

More fromSuraj

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp