如何在 swagger 3.0 中自动添加基本身份验证,而无需用户在授权按钮上输入?

2023-12-01

我正在使用 swagger 3.0,并且在 swagger 文档中有多个端点。

我希望用户不要每次都在授权按钮上输入凭据。

有什么方法可以在index.html 或我的yaml 文件中包含身份验证来自动授权用户。

Thanks.


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自动标头“尝试一下”请求。requestInterceptorSwagger 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;
  }
})
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 swagger 3.0 中自动添加基本身份验证,而无需用户在授权按钮上输入? 的相关文章

随机推荐