Adding Basic Authorization for Swagger-UI

前端 未结 4 1363
鱼传尺愫
鱼传尺愫 2020-11-30 11:14

I have currently deployed a swagger project but I am having trouble adding some basic authorization to it. Currenty when you click on the \"Try it out!\" button you are requ

4条回答
  •  囚心锁ツ
    2020-11-30 11:46

    Swagger UI 3.x

    In Swagger UI 3.13.0+, you can use the preauthorizeBasic method to pre-fill the Basic auth username and password for "try it out" calls.

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

    "Try it out" will use the specified username and password, and if you click the "Authorize" button in Swagger UI, you will see that the username and masked password are pre-filled in the UI.


    This answer also contains a solution for Swagger UI 3.1.6—3.12.1, which do not have the preauthorizeBasic feature.

提交回复
热议问题