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

Image for post
Image for post
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

Written by

Software engineer based in Stockholm, Sweden.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store