How to get Swagger to send API key as a http instead of in the URL

北慕城南 提交于 2019-11-29 23:06:09

I think that it might be a bug in swagger ui.

As a workaround, I added the following in in the swagger index.html file.

$(function () {
   $.ajaxSetup({
       beforeSend: function (jqXHR, settings) {
           jqXHR.setRequestHeader("YourApiKeyHeader", $("#input_apiKey").val());
       }
   });
});

Hope this helps,

In swagger-ui 2.0 or greater, this is trivial:

https://github.com/wordnik/swagger-ui#header-parameters

// add a new ApiKeyAuthorization when the api-key changes in the ui.
$('#input_apiKey').change(function() {
  var key = $('#input_apiKey')[0].value;
  if(key && key.trim() != "") {
    window.authorizations.add("key", new ApiKeyAuthorization("api_key", key, "header"));
  }
})

This is also much more extensible and supports custom authentication mechanisms.

you can try this

(function () {
    $(function () {
        var basicAuthUI =
                '<div class="input"><input placeholder="username" id="input_username" name="username" type="text" size="10"/></div>' +
                '<div class="input"><input placeholder="password" id="input_password" name="password" type="password" size="10"/></div>';
        $(basicAuthUI).insertBefore('#api_selector div.input:last-child');
        $("#input_apiKey").hide();

        $('#input_username').change(addAuthorization);
        $('#input_password').change(addAuthorization);
    });

    function addAuthorization() {
        SwaggerApi.supportHeaderParams = true;
        SwaggerApi.headers = {"authentication": "test"};
        var username = $('#input_username').val();
        var password = $('#input_password').val();
        if (username && username.trim() != "" && password && password.trim() != "") {
            var basicAuth = new SwaggerClient.PasswordAuthorization('basic', username, password);
            window.swaggerUi.api.clientAuthorizations.add("basicAuth", basicAuth);
            console.log("authorization added: username = " + username + ", password = " + password);
        }
    }
})();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!