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

前端 未结 1 1579
南方客
南方客 2021-01-26 20:00

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 ca

1条回答
  •  生来不讨喜
    2021-01-26 20:43

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

    0 讨论(0)
提交回复
热议问题