apiKey作为Swagger UI 2.0中的查询参数

时间:2017-06-08 05:04:20

标签: java rest swagger-ui swagger-2.0 swagger-maven-plugin

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

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

我被困的地方:我能够成功生成REST API文档。但是,REST API需要ApiKey作为Query参数。在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在窗口函数中有以下内容:

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
}

1 个答案:

答案 0 :(得分: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":[]},而忘记了&#34;安全&#34;的价值。是一个清单。

希望这会有所帮助。