Adding Basic Authorization for Swagger-UI

131.6k Views Asked by At

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 required to log in to an account to access the results. I have an account that I want to automatically be used everytime someone tries to access the api. Bellow is my index.html for the project:

    <!DOCTYPE html>
<html>
<head>
  <title>Swagger UI</title>
  <link href='css/screen.css' media='screen' rel='stylesheet' type='text/css'/>
  <link href='css/screen.css' media='print' rel='stylesheet' type='text/css'/>
  <script src='lib/jquery-1.8.3.js' type='text/javascript'></script>
  <script src='lib/jquery.slideto.min.js' type='text/javascript'></script>
  <script src='lib/jquery.wiggle.min.js' type='text/javascript'></script>
  <script src='lib/jquery.ba-bbq.min.js' type='text/javascript'></script>
  <script src='lib/handlebars-1.0.rc.1.js' type='text/javascript'></script>
  <script src='lib/underscore-min.js' type='text/javascript'></script>
  <script src='lib/backbone-min.js' type='text/javascript'></script>
  <script src='lib/swagger.js' type='text/javascript'></script>
  <script src='lib/swagger-ui.js' type='text/javascript'></script>
  <script src='lib/highlight.7.3.pack.js' type='text/javascript'></script>

  <script type="text/javascript">
    $(function () {
        window.swaggerUi = new SwaggerUi({
                discoveryUrl:"https://localhost:8080/AssistAPI/api-docs.json",
                apiKey:"",
                dom_id:"swagger-ui-container",
                supportHeaderParams: true,
                supportedSubmitMethods: ['get', 'post', 'put'],
                onComplete: function(swaggerApi, swaggerUi){
                    if(console) {
                        console.log("Loaded SwaggerUI")
                        console.log(swaggerApi);
                        console.log(swaggerUi);
                    }
                  $('pre code').each(function(i, e) {hljs.highlightBlock(e)});
                },
                onFailure: function(data) {
                    if(console) {
                        console.log("Unable to Load SwaggerUI");
                        console.log(data);
                    }
                },
                docExpansion: "none"
            });
            window.authorizations.add("key", new ApiKeyAuthorization("Authorization", "XXXX"header"));
            //window.authorizations.add("key", new ApiKeyAuthorization("username", "rmanda", "header"));
            window.swaggerUi.load();
        });
  </script>
</head>

<body class="swagger-section">
<div id='header'>
  <div class="swagger-ui-wrap">
    <a id="logo" href="http://swagger.io">swagger</a>
    <form id='api_selector'>
      <div class='input'><input placeholder="http://example.com/api" id="input_baseUrl" name="baseUrl" type="text"/></div>
      <div class='input'><input placeholder="api_key" id="input_apiKey" name="apiKey" type="text"/></div>
      <div class='input'><a id="explore" href="#">Explore</a></div>
    </form>
  </div>
</div>

<div id="message-bar" class="swagger-ui-wrap">&nbsp;</div>
<div id="swagger-ui-container" class="swagger-ui-wrap"></div>
</body>
</html>

I am trying to determine where the information is supposed to go to allow Basic Authorization. I know it involved the following lines of code, but can someone please explain to me in a little more detail where things go exactly. I have come to the realization that the documentation for swagger on GitHub is not very clear or helpful

window.authorizations.add("key", new ApiKeyAuthorization("Authorization", "XXXX"header"));
window.authorizations.add("key", new ApiKeyAuthorization("username", "password", "header"));
4

There are 4 best solutions below

0
On

I had a similar problem, the suggested answers are correct in my case I end up adding something in the index.html like:

var myAuth = "Basic " + btoa("user:password");
window.authorizations.add("key", neSwaggerClient.ApiKeyAuthorization("Authorization", myAuth, "header"));

I added this on either the marked method addApiKeyAuthorization or you can create another method but call it after the window.swaggerUi.load();

But if you have your swagger-ui running as "stand alone" with something like gulp or grunt you may require to configure the services to accept all OPTIONS request.

I struggle a little with that, I hope it helps someone.

Regards

1
On

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.

0
On

you can add/change this function in your dist/index.html file

function addApiKeyAuthorization(){
    var key = encodeURIComponent($('#input_apiKey')[0].value);
    if(key && key.trim() != "") {
        key = 'Basic '+key;
        var apiKeyAuth = new SwaggerClient.ApiKeyAuthorization("Authorization", key, "header");
        window.swaggerUi.api.clientAuthorizations.add("Authorization", apiKeyAuth);
        log("added key " + key);
    }
  }

OR you can move on new version of Swagger 2.0 , this is known issue is was fixed.

1
On

The correct setting for Basic authentication Header is:

Authorization: Basic username:password

The String username:password needs to be encoded using RFC2045-MIME a variant of Base64. See more details here: https://en.wikipedia.org/wiki/Basic_access_authentication#Client_side

Then, to configure this header, you should do:

Considering that the Base64 encoding for username:password is dXNlcm5hbWU6cGFzc3dvcmQ=

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

Read more about this here: https://github.com/swagger-api/swagger-ui