How do I automatically authorize all endpoints with Swagger UI?
Solution 1:
For those using Swagger UI 3.x (more specifically, v.3.13.0+) – you can use the following methods to authorize automatically:
-
preauthorizeBasic
– for Basic auth -
preauthorizeApiKey
– for API keys and OAS3 Bearer auth
To use these methods, the corresponding security schemes must be defined in your API definition. For example:
openapi: 3.0.0
...
components:
securitySchemes:
basicAuth:
type: http
scheme: basic
api_key:
type: apiKey
in: header
name: X-Api-Key
security:
- basicAuth: []
- api_key: []
Call preauthorizeNNN
from the onComplete
handler, like so:
// index.html
const ui = SwaggerUIBundle({
url: "https://my.api.com/swagger.yaml",
...
onComplete: function() {
// Default basic auth
ui.preauthorizeBasic("basicAuth", "username", "password");
// Default API key
ui.preauthorizeApiKey("api_key", "abcde12345");
}
})
In this example, "basicAuth" and "api_key" are the keys name of the security schemes as specified in the API definition.
Solution 2:
I found a solution, using PasswordAuthorization
instead of ApiKeyAuthorization
.
The correct thing to do is to add the following line into the onComplete
handler:
swaggerUi.api.clientAuthorizations.add("basicAuth",
new SwaggerClient.PasswordAuthorization(
"8939927d-4b8a-4a69-81e4-8290a83fd2e7",
"fbb7a689-2bb7-4f26-8697-d15c27ec9d86"));
swaggerUi
is passed to the callback so this is the value to use. Also, make sure the name of your auth object matches the name in the YAML file.