如何在swagger 3.0中自动添加基本身份验证,而无需用户在授权按钮上键入? [英] How Can I add basic auth in swagger 3.0 automatically with out the user to type in at authorize button?

查看:5101
本文介绍了如何在swagger 3.0中自动添加基本身份验证,而无需用户在授权按钮上键入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用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标头以尝试"请求. Swagger UI 3.1.6和更高版本支持requestInterceptor.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆