Swagger UI 3.13.0+ 提供了preauthorizeBasic
用于此目的的方法。假设您的 API 定义包含基本身份验证的安全方案:
swagger: '2.0'
...
securityDefinitions:
basicAuth:
type: basic
security:
- basicAuth: []
您可以为基本身份验证指定默认用户名和密码,如下所示:
// 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");
}
})
现在,如果您单击 Swagger UI 中的“授权”按钮,您将看到用户名和密码已预先填写。
Original answer (for Swagger UI 3.1.6—3.12.1):
您可以添加requestInterceptor到您的 Swagger UI索引.html文件以添加Authorization
自动标头“尝试一下”请求。requestInterceptor
Swagger UI 3.1.6 及更高版本支持。
// 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;
}
})