如何在 swagger ui v.3.0 中使用基本身份验证 [英] How to use Basic auth in swagger ui v.3.0
问题描述
在 swagger ui 2.0 中是代码
in swagger ui 2.0 it was code
var basicAuth = new SwaggerClient.PasswordAuthorization("basicAuth", username, password);
window.swaggerUi.api.clientAuthorizations.add("basicAuth", basicAuth);
有人可以提供 swagger ui 3.0 版本的代码吗?
Can somebody provide code for version swagger ui 3.0?
谢谢.
编辑.我正在尝试做这样的事情 - 为 Swagger-UI 添加基本授权
Edit. i`m trying to do something like this - Adding Basic Authorization for Swagger-UI
我在具有基本身份验证的服务器上使用 Swagger.所以我无法初始化库.
I`m using Swagger on server with Basic auth. SO i cant init library.
const ui = SwaggerUIBundle({
url: "http://petstore.swagger.io/v2/swagger.json",
dom_id: '#swagger-ui',
presets: [
SwaggerUIBundle.presets.apis,
// yay ES6 modules ↘
Array.isArray(SwaggerUIStandalonePreset) ? SwaggerUIStandalonePreset : SwaggerUIStandalonePreset.default
],
plugins: [
SwaggerUIBundle.plugins.DownloadUrl
],
layout: "StandaloneLayout"
})
window.ui = ui
没有基本身份验证一切正常.
without basic auth everything works fine.
已启用基本身份验证 - http://prntscr.com/enxee4
basic auth enabled - http://prntscr.com/enxee4
推荐答案
在 Swagger UI 3.x 中,版本支持获取受基本身份验证/API 密钥保护的规范(.yaml/.json 文件).3.3.2 及更高版本.在您的 Swagger UI 初始化代码中,定义一个 requestinterceptor
将身份验证标头附加到规范获取请求:
In Swagger UI 3.x, fetching specs (.yaml/.json files) protected with Basic auth / API keys is supported in ver. 3.3.2 and later. In your Swagger UI initialization code, define a requestinterceptor
that attaches auth headers to the spec fetch request:
<!-- index.html -->
const ui = SwaggerUIBundle({
url: "http://petstore.swagger.io/v2/swagger.json",
requestInterceptor: (req) => {
if (req.loadSpec) {
// Fetch the spec using Basic auth, replace "user" and "password" with yours
req.headers.Authorization = 'Basic ' + btoa('user:password');
// or API key
// req.headers.MyApiKey = 'abcde12345';
// or bearer token
// req.headers.Authorization = 'Bearer abcde12345';
}
return req;
},
...
})
这篇关于如何在 swagger ui v.3.0 中使用基本身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!