How to add Header with Authorization for springdoc-openapi endpoint calls
Asked Answered
S

4

14

Swagger2 (springfox) worked with:

@Bean
public Docket getDocket() {
    return new Docket(DocumentationType.SWAGGER_2)
        .select()
        .apis(RequestHandlerSelectors.withClassAnnotation(RestController.class))
        .apis(RequestHandlerSelectors.any())
        .paths(PathSelectors.any())
        .build()
        .useDefaultResponseMessages(false)
        .globalOperationParameters(Collections.singletonList(getAuthHeader()));
}

private Parameter getAuthHeader() {
    return new ParameterBuilder()
        .parameterType("header")
        .name("Authorization")
        .modelRef(new ModelRef("string"))
        .defaultValue(getBase64EncodedCredentials())
        .build();
}

private String getBase64EncodedCredentials() {
    String auth = authUser.getUser() + ":" + authUser.getPassword();
    byte[] encodedAuth = Base64.encode(auth.getBytes(StandardCharsets.UTF_8));
    return "Basic " + new String(encodedAuth, Charset.defaultCharset());
}

Springdoc-openapi:

@Bean
public OpenAPI getOpenAPI() {
    return new OpenAPI().components(new Components()
        .addHeaders("Authorization", new Header().description("Auth header").schema(new StringSchema()._default(getBase64EncodedCredentials()))));
}

I can't achieve it for springdoc-openapi. It seems the header is not working.

Seacoast answered 29/5, 2020 at 20:10 Comment(1)
Did you figure this out. I have just integrated springdoc-openapi-ui into a spring boot app. But while it can display the swagger ui for all my endpoints, I have no option to add an authorization header to each request @SeacoastGenteelism
J
14

For Authorization header to work, it is also required to have security in the root of the specification.

For example, below code would set JWT bearer token in the Authorization header.

@Bean
public OpenAPI customOpenAPI(@Value("${openapi.service.title}") String serviceTitle, @Value("${openapi.service.version}") String serviceVersion) {
    final String securitySchemeName = "bearerAuth";
    return new OpenAPI()
            .components(
                    new Components()
                            .addSecuritySchemes(securitySchemeName,
                                    new SecurityScheme()
                                            .type(SecurityScheme.Type.HTTP)
                                            .scheme("bearer")
                                            .bearerFormat("JWT")
                            )
            )
            .security(List.of(new SecurityRequirement().addList(securitySchemeName)))
            .info(new Info().title(serviceTitle).version(serviceVersion));
}

Generated specification yml will be as below -

security:
  - bearerAuth: []
...
components:
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      bearerFormat: JWT

So, based on above specification, below part leads to Authorization header

  security:
    - bearerAuth: []
Jaclin answered 22/6, 2022 at 12:33 Comment(0)
U
13

Adding parameter definition to a custom OpenAPI bean will not work because the parameter won't get propagated to the operations definitions. You can achieve your goal using OperationCustomizer:

@Bean
public OperationCustomizer customize() {
    return (operation, handlerMethod) -> operation.addParametersItem(
            new Parameter()
                    .in("header")
                    .required(true)
                    .description("myCustomHeader")
                    .name("myCustomHeader"));
}

The OperationCustomizer interface was introduced in the springdoc-openapi 1.2.22.

Unwearied answered 21/10, 2021 at 6:28 Comment(0)
S
11

The behaviour you are describing is not related to springdoc-openapi. But to swagger-ui which respects the OpenAPI Spec as well:

Settera answered 30/5, 2020 at 13:27 Comment(0)
P
1

We can do this using following

import io.swagger.v3.oas.annotations.OpenAPIDefinition;
import io.swagger.v3.oas.annotations.enums.SecuritySchemeIn;
import io.swagger.v3.oas.annotations.enums.SecuritySchemeType;
import io.swagger.v3.oas.annotations.info.Info;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.security.SecurityScheme;
import org.springframework.context.annotation.Configuration;

@Configuration
@OpenAPIDefinition(info = @Info(title = "Secured Test App"), security = @SecurityRequirement(name = "bearerAuth"))
@SecurityScheme(type = SecuritySchemeType.HTTP, bearerFormat = "jwt", name = "bearerAuth", scheme = "bearer", in = SecuritySchemeIn.HEADER)
class SpringDocSwaggerConfig {

}
Proteose answered 5/6 at 17:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.