For the last 2 days, I was facing a issue with setting Global Request headers to Springfox’s Swagger-UI (version 2.8.0) for a SpringBoot Application.
The issue was more related to the new Swagger version 2.8.0 and does not any issues in prior versions. In the below code, I am only presenting the cause and the solution. Assuming the developers have prior knowledge of Swagger and its implementation. More implementation details can be found at https://springfox.github.io/springfox/docs/current/#quick-start-guides
@Bean public Docket apiSwaggerDocket() { return new Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.withClassAnnotation(Api.class)) .paths(PathSelectors.any()) .build() .pathMapping("/") .genericModelSubstitutes(ResponseEntity.class) .useDefaultResponseMessages(false) .forCodeGeneration(true) .securitySchemes(newArrayList(apiKey())) .apiInfo(apiInfo()); private ApiKey apiKey() { return new ApiKey("access_token", "access_token", "header"); }
Let’s only concentrate on the apiKey() method. The new ApiKey(…) constructor has different argument signatures for different versions of springfox’s swagger.
/** * http://springfox.github.io/springfox/javadoc/current/springfox/documentation/service/ApiKey.html * Signature of the ApiKey constructor * return new ApiKey(name, keyName, passAs); * * name - is the name of the key * keyName - is the value of the key name * passAs - you can pass as header or query parameter */ // For version 2.6.0 return new ApiKey("Authorization", "Bearer", "header"); Output at swagger-ui name: Authorization in: header value: Bearer // For version 2.7.0 - This version has reverse the constructor Argument signature return new ApiKey("Authorization", "Bearer", "header"); Output at swagger-ui name: Authorization in: header value: Bearer // For version 2.8.0 return new ApiKey("Authorization", "Bearer", "header"); Output at swagger-ui There is no header displayed in this version of the swagger.
For my current use case, I had to step down the swagger version to 2.7.0.
Alternatively, if one intends to use version 2.8.0, we can have globalOperationParameters to put in use, with all API’s requesting for header
@Bean public Docket apiSwaggerDocket() { return new Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.withClassAnnotation(Api.class)) .paths(PathSelectors.any()) .build() .pathMapping("/") .genericModelSubstitutes(ResponseEntity.class) .useDefaultResponseMessages(false) .forCodeGeneration(true) .apiInfo(apiInfo()) .globalOperationParameters( newArrayList(new ParameterBuilder() .name("access_token") .description("Access Token") .modelRef(new ModelRef("string")) .parameterType("header") .required(true) .build())); }
The only drawback using globalOperationParameters, the header is not sticky. Meaning, the same header value is required for each and every API in Swagger, which is not great.
Thanks for reading my post 🙂
More Reading & Resources: