18

How to enable "Authorize" button in springdoc-openapi-ui (OpenAPI 3.0 /swagger-ui.html) for Basic Authentication.

What annotations have to be added to Spring @Controller and @Configuration classes?

Authorize button

Authorize form for Basic Authentication

Eugene Khyst
  • 9,236
  • 7
  • 38
  • 65
  • 1
    [Adding Basic Auth authorization option to OpenAPI/Swagger documentation — Java Spring | by Hamza Sabljakovic | Medium](https://sabljakovich.medium.com/adding-basic-auth-authorization-option-to-openapi-swagger-documentation-java-spring-95abbede27e9) – Jason Law Mar 06 '22 at 12:04

1 Answers1

27

Define a global security scheme for OpenAPI 3.0 using annotation @io.swagger.v3.oas.annotations.security.SecurityScheme in a @Configuration bean:

@Configuration
@OpenAPIDefinition(info = @Info(title = "My API", version = "v1"))
@SecurityScheme(
    name = "basicAuth",
    type = SecuritySchemeType.HTTP,
    scheme = "basic"
)
public class OpenApi30Config {

}

Annotate @RestController with @SecurityRequirement(name = "basicAuth")

@RestController
@SecurityRequirement(name = "basicAuth")
public class Controller {}

OR

Annotate each @RestController method requiring Basic Authentication with @io.swagger.v3.oas.annotations.Operation referencing the defined security scheme:

@Operation(summary = "My endpoint", security = @SecurityRequirement(name = "basicAuth"))
littl3rud3
  • 67
  • 7
Eugene Khyst
  • 9,236
  • 7
  • 38
  • 65
  • 3
    How to apply it to all APIs? **Edit:** I just got this link https://stackoverflow.com/a/60666209/3249330 – Mohit Sharma Jul 03 '20 at 17:40
  • 1
    @Evgeniy I Tried what you have mentioned the UI comes up but no matter what user id password i give it says authorized. any idea? – Vishesh Sep 02 '21 at 10:49