Swagger UI 3.13.0+ provides the preauthorizeBasic
method for this purpose. Assuming your API definition includes a security scheme for Basic auth:
swagger: '2.0'
...
securityDefinitions:
basicAuth:
type: basic
security:
- basicAuth: []
you can specify the default username and password for Basic auth like so:
// index.html
const ui = SwaggerUIBundle({
url: "https://my.api.com/swagger.yaml",
...
onComplete: function() {
// "basicAuth" is the key name of the security scheme in securityDefinitions
ui.preauthorizeBasic("basicAuth", "username", "password");
}
})
Now, if you click the "Authorize" button in Swagger UI, you will see that the username and password are pre-filled.
Original answer (for Swagger UI 3.1.6—3.12.1):
You can add the requestInterceptor
to your Swagger UI's index.html file in order to add the Authorization
header automatically to "try it out" requests. requestInterceptor
is supported in Swagger UI 3.1.6 and later.
// index.html
const ui = SwaggerUIBundle({
url: "http://my.api.com/swagger.yaml",
...
requestInterceptor: (req) => {
if (! req.loadSpec) {
// Add the header to "try it out" calls but not spec fetches
var token = btoa("username" + ":" + "password");
req.headers.Authorization = "Basic " + token;
}
return req;
}
})