Adding Basic Auth authorization option to OpenAPI/Swagger documentation — Java Spring
This is a short guide on how to enable Open API/Swagger UI support for Basic Auth. To further clarify, this will NOT protect your APIs with a Basic Auth mechanism but rather give you a way to modify Open API/Swagger configuration to reflect APIs that are already protected with the mentioned method.
We will assume you have already successfully setup the OpenAPI/Swagger documentation for your project and the focus will be on the Basic Auth part of the configuration. Worth mentioning is that the following example is built using a great docs library — springdoc.org.
All the configuration is done in a single place and everything required can be achieved with the following three annotations.
The above settings are global, which means it will be applied to all the endpoints. However, there are cases when we have to use multiple authentication methods, let’s say the main auth mechanism is OAuth2 but the /health
endpoint (utilized for the internal operations) needs Basic Auth. That as well can be achieved in a very simple way.
This configuration requires adding the @Operation
annotation on the request handler method and specifying the schema name — the one defined in the @SecurityScheme
anotation.
Of course, the configuration bean now needs to be updated to remove the section that makes it global.