如何让 Swagger 将 API 密钥作为 http 而不是在 URL 中发送 [英] How to get Swagger to send API key as a http instead of in the URL

查看:23
本文介绍了如何让 Swagger 将 API 密钥作为 http 而不是在 URL 中发送的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

除非我弄错了,根据文档我应该将 supportHeaderParams 设置为 true以及从我的 html 页面初始化 Swagger 时 JSON 参数中的 apiKeyNameapiKey 值.

Unless I'm mistaken, according to the documentation I should set supportHeaderParams to true as well as the apiKeyName and apiKey value in the JSON parameters when initializing Swagger from my html page.

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

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.

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

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

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

不幸的是,我根本没有得到任何标题,没有Api-Key"或testheader".

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

推荐答案

我觉得可能是swagger ui的bug.

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

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

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

希望这会有所帮助,

这篇关于如何让 Swagger 将 API 密钥作为 http 而不是在 URL 中发送的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆