Adding Basic Auth authorization option to OpenAPI/Swagger documentation — Java Spring

Hamza Sabljakovic
2 min readJan 1, 2021

--

Authorize button for basic auth

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.

Adds global basic auth authorization option

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.

Basic auth authorization on a specific endpoint

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.

Example configuration of a basic auth authorization applied to a single endpoint

--

--

Hamza Sabljakovic
Hamza Sabljakovic

Written by Hamza Sabljakovic

Software engineer based in Stockholm, Sweden.

Responses (1)