How to use Basic auth in swagger ui v.3.0

in swagger ui 2.0 it was code

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

Can someone provide code for swagger ui 3.0 version?

Thanks.

Change I'm trying to do something like this - Adding basic authorization for Swagger-UI

I am using Swagger on a 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

+6
source share
2 answers

I am creating index.html with a simple form to populate user credentials to get the session id. Then, for example, redirect the swagger.html file 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"));

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

, .

+2

Swagger UI 3.x ( .yaml/.json), auth/API, . 3.3.2 . Swagger UI requestinterceptor, auth :

<!-- 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;
  },
  ...
})
+2

Source: https://habr.com/ru/post/1015987/


All Articles