How Can I add basic auth in swagger 3.0 automatically with out the user to type in at authorize button?

前提是你 提交于 2019-12-24 12:00:38

问题


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.

Is there any way I can include authentication in index.html or in my yaml files to automatically authorize the user.

Thanks.


回答1:


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");
  }
})

Now, if you click the "Authorize" button in Swagger UI, you will see that the username and password are pre-filled.



Original answer (for Swagger UI 3.1.6—3.12.1):

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;
  }
})


来源:https://stackoverflow.com/questions/49422437/how-can-i-add-basic-auth-in-swagger-3-0-automatically-with-out-the-user-to-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!