如何在没有用户在授权按钮处输入的情况下自动在 swagger 3.0 中添加基本身份验证? [英] How Can I add basic auth in swagger 3.0 automatically with out the user to type in at authorize button?
问题描述
我正在使用 swagger 3.0,并且在 swagger 文档中有多个端点.
I am using swagger 3.0 and have multiple endpoints in swagger docs.
我希望用户不要每次都在授权按钮处输入凭据.
I want user not to type in credentials at authorize button every time.
有什么方法可以在 index.html 或我的 yaml 文件中包含身份验证以自动授权用户.
Is there any way I can include authentication in index.html or in my yaml files to automatically authorize the user.
谢谢.
推荐答案
Swagger UI 3.13.0+ 为此提供了 preauthorizeBasic
方法.假设您的 API 定义包含基本身份验证的安全方案:
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");
}
})
现在,如果您在 Swagger UI 中单击授权"按钮,您将看到用户名和密码已预先填写.
Now, if you click the "Authorize" button in Swagger UI, you will see that the username and password are pre-filled.
原始答案(适用于 Swagger UI 3.1.6-3.12.1):
Original answer (for Swagger UI 3.1.6—3.12.1):
您可以添加 requestInterceptor
添加到 Swagger UI 的 index.html 文件中,以便自动将 Authorization
标头添加到试用"请求中.requestInterceptor
在 Swagger UI 3.1.6 及更高版本中受支持.
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;
}
})
这篇关于如何在没有用户在授权按钮处输入的情况下自动在 swagger 3.0 中添加基本身份验证?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!