How do I automatically authorize all endpoints with Swagger UI?

☆樱花仙子☆ 提交于 2020-02-24 05:42:55

问题


I have an entire API deployed and accessible with Swagger UI. It uses Basic Auth over HTTPS, and one can easily hit the Authorize button and enter credentials and things work great with the nice Try it out! feature.

However, I would like to make a public sandboxed version of the API with a shared username and password, that is always authenticated; that is, no one should ever have to bring up the authorization dialog to enter credentials.

I tried to enter an authorization based on the answer from another Stack Overflow question by putting the following code inside a script element on the HTML page:

window.swaggerUi.load();
swaggerUi.api.clientAuthorizations.add("key", 
  new SwaggerClient.ApiKeyAuthorization(
  "Authorization", "Basic dXNlcm5hbWU6cGFzc3dvcmQ=", "header"));

However, when I hit the Try it out! button the authorization is not used.

What would be the proper way to go about globally setting the auth header on all endpoints, so that no user has to enter the credentials manually?

(I know that might sound like a weird question, but like I mention, it is a public username/password.)


回答1:


For those using Swagger UI 3.x (more specifically, v.3.13.0+) – you can use the following methods to authorize automatically:

  • preauthorizeBasic – for Basic auth
  • preauthorizeApiKey – for API keys and OAS3 Bearer auth

To use these methods, the corresponding security schemes must be defined in your API definition. For example:

openapi: 3.0.0
...
components:
  securitySchemes:

    basicAuth:
      type: http
      scheme: basic

    api_key:
      type: apiKey
      in: header
      name: X-Api-Key

security:
  - basicAuth: []
  - api_key: []

Call preauthorizeNNN from the onComplete handler, like so:

// index.html

const ui = SwaggerUIBundle({
  url: "https://my.api.com/swagger.yaml",
  ...

  onComplete: function() {

    // Default basic auth
    ui.preauthorizeBasic("basicAuth", "username", "password");

    // Default API key
    ui.preauthorizeApiKey("api_key", "abcde12345");
  }
})

In this example, "basicAuth" and "api_key" are the keys name of the security schemes as specified in the API definition.




回答2:


I found a solution, using PasswordAuthorization instead of ApiKeyAuthorization.

The correct thing to do is to add the following line into the onComplete handler:

      swaggerUi.api.clientAuthorizations.add("basicAuth",
        new SwaggerClient.PasswordAuthorization(
          "8939927d-4b8a-4a69-81e4-8290a83fd2e7",
          "fbb7a689-2bb7-4f26-8697-d15c27ec9d86"));

swaggerUi is passed to the callback so this is the value to use. Also, make sure the name of your auth object matches the name in the YAML file.



来源:https://stackoverflow.com/questions/45199989/how-do-i-automatically-authorize-all-endpoints-with-swagger-ui

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