0

上下文:将 Swagger 从 1.2 规范中的当前 REST 文档转换为 2.0

环境:Java 8,swagger-maven-plugin 3.0.1,swagger annotations (com.wordnik)

我被困在哪里:我能够成功生成 REST API 文档。但是,REST API 需要一个 ApiKey 作为查询参数。在 1.2 规范中,这是使用 index.html 中的以下代码段添加的

function addApiKeyAuthorization() {
    var key = $('#input_apiKey')[0].value;
    log("key: " + key);
    if(key && key.trim() != "") {
        log("added key " + key);
        //window.authorizations.add("api_key", new ApiKeyAuthorization("api_key", key, "query"));
        window.authorizations.add("apiKey", new ApiKeyAuthorization("apiKey", key, "header"));
    }
  }

  $('#input_apiKey').change(function() {
    addApiKeyAuthorization();
  });

  // if you have an apiKey you would like to pre-populate on the page for demonstration purposes...

    var apiKey = "ABCD";
    $('#input_apiKey').val(apiKey);
    addApiKeyAuthorization();

但是,对于 2.0 规范,我的搜索导致 yaml 文件发生以下更改。

securityDefinitions:
 UserSecurity:
  type: apiKey
  in: header
  name:myApiKey

当前的 index.html 有以下 in window 函数:

window.onload = function() {
  // Build a system
  const ui = SwaggerUIBundle({
    url: "http://someCoolsite.com/swagger.json",
    dom_id: '#swagger-ui',
    presets: [
      SwaggerUIBundle.presets.apis,
      SwaggerUIStandalonePreset
    ],
    plugins: [
      SwaggerUIBundle.plugins.DownloadUrl
    ],
    layout: "StandaloneLayout"
  })
  window.ui = ui
}
4

1 回答 1

0

经过进一步探索,我找到了上述问题的答案。

首先:我的 index.html 如下:

<script>
$(function(){
  window.onload = function() {
  // Build a system
  const ui = SwaggerUIBundle({
    url: "http://www.webhostingsite.com/swagger.json",
    dom_id: '#swagger-ui',
    presets: [
      SwaggerUIBundle.presets.apis,
      SwaggerUIStandalonePreset
    ],
    plugins: [
      SwaggerUIBundle.plugins.DownloadUrl
    ],
    layout: "StandaloneLayout"
  })
  window.ui = ui
}
window.onFailure = function(data) {
    log("Unable to Load SwaggerUI");
}

function addApiKeyAuthorization() {
  var key = $('#input_apiKey')[0].value;
  log("key: " + key);
  if(key && key.trim() != "") {
    log("added key " + key);
    //window.authorizations.add("api_key", new ApiKeyAuthorization("api_key", key, "query"));
    window.authorizations.add("apiKey", new ApiKeyAuthorization("apiKey", key, "query"));
  }
}

$('#input_apiKey').change(function() {
  addApiKeyAuthorization();
});
});

然后,我将我的 swagger.json 更新为如下:

   {
  "swagger" : "2.0",
  "securityDefinitions": {
    "apiKey": {
     "type": "apiKey",
     "name": "apiKey",
      "in": "query"
    }
  },
  "host" : "<api base path>",
  "basePath" : "/v1",
  "security": [{"apiKey": []}]", //Global security (applies to all operations)
  .......

第三:在 AWS S3 上托管 index.html 和 swagger.json 用于静态 Web 托管。

我出错的部分是,"security": [{"apiKey": []}]".

我一直"security":{"apiKey":[]}在忘记“安全”的价值是一个列表。

希望这可以帮助。

于 2017-06-12T05:17:42.090 回答