如何在用户不输入授权按钮的情况下自动在 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 文档中有多个端点。

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

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

谢谢。

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 中单击 "Authorize" 按钮,您将看到用户名和密码为 pre-filled。



原始答案(对于 Swagger UI 3.1.6—3.12.1):

您可以将 requestInterceptor 添加到您的 Swagger UI 的 index.html 文件中,以便添加 Authorization header 自动向 "try it out" 请求。 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;
  }
})