javascript 如何让 Swagger 将 API 密钥作为 http 而不是 URL 发送

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16899515/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 06:24:38  来源:igfitidea点击:

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

javascriptservicestackswagger

提问by Rob Bird

I am using swagger with servicestackbut I am getting a 401 unauthorised error from my /resources URL becuase it requires an API key.

我正在将 swagger 与servicestack一起使用,但我从我的 /resources URL 收到 401 未经授权的错误,因为它需要一个 API 密钥。

Unless I'm mistaken, according to the documentationI should set supportHeaderParamsto true as well as the apiKeyNameand apiKeyvalue in the JSON parameters when initializing Swagger from my html page.

除非我记错了,根据文档我应该设置supportHeaderParams为真还有apiKeyNameapiKey从我的html页面初始化时扬鞭值在JSON参数。

I was then expecting to see my API key in the http request headers, but it is still being appended to the URL and not in the headers collection.

然后我期待在 http 请求标头中看到我的 API 密钥,但它仍然被附加到 URL 而不是在标头集合中。

Here is the code that initialises Swagger in my HTML page:

这是在我的 HTML 页面中初始化 Swagger 的代码:

 window.swaggerUi = new SwaggerUi({
            discoveryUrl: "http://pathtomyservice.com/resources",
                headers: { "testheader" : "123" },
                apiKey: "123",
                apiKeyName: "Api-Key",
                dom_id:"swagger-ui-container",
                supportHeaderParams: true,
                supportedSubmitMethods: ['get', 'post', 'put', 'delete'],
                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"
            });

Unfortunately I get no headers at all, no 'Api-Key' or 'testheader'.

不幸的是,我根本没有标题,没有“Api-Key”或“testheader”。

回答by gsimoes

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

我认为这可能是 swagger ui 中的一个错误。

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

作为一种解决方法,我在 swagger index.html 文件中添加了以下内容。

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

Hope this helps,

希望这可以帮助,

回答by fehguy

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

在 swagger-ui 2.0 或更高版本中,这是微不足道的:

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

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.

这也更具可扩展性,并支持自定义身份验证机制。

回答by Tuan Minh

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