How to use Basic auth in swagger ui v.3.0

后端 未结 3 1541
伪装坚强ぢ
伪装坚强ぢ 2020-12-31 15:47

in swagger ui 2.0 it was code

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


        
3条回答
  •  情歌与酒
    2020-12-31 16:11

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

提交回复
热议问题