9

in swagger ui 2.0 it was code

var basicAuth = new SwaggerClient.PasswordAuthorization("basicAuth", username, password);
window.swaggerUi.api.clientAuthorizations.add("basicAuth", basicAuth);

Can somebody provide code for version swagger ui 3.0?

Thanks.

Edit. i`m trying to do something like this - Adding Basic Authorization for Swagger-UI

I`m using Swagger on server with Basic auth. SO i cant init library.

  const ui = SwaggerUIBundle({
url: "http://petstore.swagger.io/v2/swagger.json",
dom_id: '#swagger-ui',
presets: [
  SwaggerUIBundle.presets.apis,
  // yay ES6 modules ↘
  Array.isArray(SwaggerUIStandalonePreset) ? SwaggerUIStandalonePreset : SwaggerUIStandalonePreset.default
],
plugins: [
  SwaggerUIBundle.plugins.DownloadUrl
],
layout: "StandaloneLayout"
  })

window.ui = ui

without basic auth everything works fine.

basic auth enabled - http://prntscr.com/enxee4

Community
  • 1
  • 1
Alex
  • 213
  • 1
  • 3
  • 9
  • Do you mean loading a Swagger spec (.json/.yaml) that is protected by Basic auth? Or do you want to auto-add the Authorization header to all "try it out" requests? – Helen Mar 24 '17 at 14:19
  • @Helen first. Swagger spec (.json/.yaml) that is protected by Basic auth – Alex Mar 24 '17 at 14:23
  • I think UI v3 does not support this for now. You can open an issue in the [GitHub repo](https://github.com/swagger-api/swagger-ui/issues). – Helen Mar 24 '17 at 14:36
  • 3
    Issue was created https://github.com/swagger-api/swagger-ui/issues/2793 – Alex Mar 27 '17 at 07:49

3 Answers3

4

In Swagger UI 3.x, fetching specs (.yaml/.json files) protected with Basic auth / API keys is supported in ver. 3.3.2 and later. In your Swagger UI initialization code, define a requestinterceptor that attaches auth headers to the spec fetch request:

<!-- index.html -->

const ui = SwaggerUIBundle({
  url: "http://petstore.swagger.io/v2/swagger.json",

  requestInterceptor: (req) => {
    if (req.loadSpec) {
        // Fetch the spec using Basic auth, replace "user" and "password" with yours
        req.headers.Authorization = 'Basic ' + btoa('user:password');

        // or API key
        // req.headers.MyApiKey = 'abcde12345';

        // or bearer token
        // req.headers.Authorization = 'Bearer abcde12345';
    }
    return req;
  },
  ...
})
Helen
  • 87,344
  • 17
  • 243
  • 314
2

I build an index.html with a simple form to fill user credentials to get a session id. Then redirect to swagger.html, for instance, and make some changes.

Before window.onload:

var orgFetch;

window.setExtraHeader = function(sessionId) {
    var system = window.ui.getSystem();

    if(!system) return;

    if(!orgFetch) {
        orgFetch = system.fn.fetch;
    }

    system.fn.fetch = function(obj) {
        if(!obj) return;

        if(!obj.headers) {
            obj.headers = {};
        }

        obj.headers['sessionId'] = sessionId;

        return orgFetch(obj)
            .then(function(fetchRes) {
                return fetchRes;
            });
    }

    system.specActions.download();
}

and then:

window.ui = ui;
window.setExtraHeader(localStorage.getItem("sessionId"));

Source: https://github.com/swagger-api/swagger-ui/issues/2793

Hope this helps.

marcos
  • 157
  • 4
  • 14
0

In swagger-ui 3.2x, to manually set Authorization header based on values entered in the authorize popup for basic authentication, we can use below code.

const ui = SwaggerUIBundle({
        dom_id: '#swagger-ui',
        requestInterceptor: (req) => {
        if (!req.loadSpec) {
            var authorized = this.ui.authSelectors.authorized();
            //'Basic_Authentication' is security scheme key for basic authentication in the OpenApi file
            var basicAuth = getEntry(authorized, 'Basic_Authentication');
            if (basicAuth) {
                var basicAuthValue = getEntry(basicAuth, 'value');
                if (basicAuthValue) {
                    var username = getEntry(basicAuthValue, 'username');
                    var password = getEntry(basicAuthValue, 'password');
                    if (username && password) {
                        req.headers.Authorization = "Basic " + btoa(username + ":" + password); 
                    }
                }
            }
        }
        return req;
    }

//traverse through the object structure of swagger-ui authorized object to get value for an entryName
    function getEntry(complexObj, entryName) {
        if (complexObj && complexObj._root && complexObj._root.entries) {
            var objEntries = complexObj._root.entries;
            for (var t = 0; t < objEntries.length; t++) {
                var entryArray = objEntries[t];
                if (entryArray.length > 1) {
                    var name = entryArray[0];
                    if (name === entryName) {
                        return entryArray[1];
                    }
                }
            }
        }

        return null;
        }
Sachintha
  • 13
  • 2