Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 508
Ray Toal Avatar asked Dec 19 '22 05:12

Ray Toal


1 Answers

If you use Swagger UI v.3.13.0 or later, you can use the following methods to authorize the endpoints automatically:

  • preauthorizeBasic – for Basic auth
  • preauthorizeApiKey – for API keys and OpenAPI 3.x 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

    bearerAuth:
      type: http
      scheme: bearer

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

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

    // Default Bearer token
    ui.preauthorizeApiKey("bearerAuth", "your_bearer_token");
  }
})

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

like image 164
Helen Avatar answered Dec 28 '22 06:12

Helen