Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

basic authentication - How do I automatically authorize all endpoints with Swagger UI?

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.)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...