如何在Swagger

时间:2016-08-22 11:55:19

标签: node.js express swagger swagger-2.0

我尝试了几种方法来向Swagger添加基本的API密钥授权(表达swagger)。以下是我的清单中的相关信息。

{
  ...
  "main": "app.js",
  "dependencies": {
    "express": "^4.12.3",
    "swagger-express-mw": "^0.1.0"
  },
  ...
}

我相信我已经在YAML配置中注册了安全定义。

swagger: "2.0"
info:
  ...

# Set up security for the API
securityDefinitions:
  defaultApiKey:
    type: apiKey
    in: header
    name: defaultApiKey

security:
    - defaultApiKey: []

要完成此配置,我想我只需要在SwaggerExpress.create()函数中注册中间件。以下是我目前的整个app.js。

'use strict';

var SwaggerExpress = require('swagger-express-mw');
var app = require('express')();
module.exports = app; // for testing

var config = {
  appRoot: __dirname // required config
};

SwaggerExpress.create(config, function(err, swaggerExpress) {
  if (err) { throw err; }

  // Serve the Swagger documents and SwaggerUi
  app.use(swaggerExpress.runner.swaggerTools.swaggerUi());

  // Install security
  app.use(swaggerExpress.swaggerSecurity({
    defaultApiKey: function(req, def, scopes, callback) {
      console.log("hit");
    }
  }));

  // install middleware
  swaggerExpress.register(app);

  var port = process.env.PORT || 10010;
  app.listen(port);
});

当我尝试使用它时,我会看到以下内容:

Error initializing middleware
TypeError: swaggerExpress.swaggerSecurity is not a function

我尝试过几种不同的配置方法但没有成功。我是否在YAML中正确定义了API密钥,如果是,我该如何在app.js文件中注册API密钥处理程序?

2 个答案:

答案 0 :(得分:3)

有点晚了,但供将来参考。 使用swagger-express-mw,这就是你可以做到的(它对我有用):

config: {
    appRoot: __dirname,
    swaggerSecurityHandlers: {
        defaultApiKey: function(req, authOrSecDef, scopesOrApiKey, callback) {
        // code here
        }
    }
}

我希望这对某人有帮助。

答案 1 :(得分:1)

我能够通过将YAML定义转换为JSON格式并以这种方式加载API定义来克服此问题:

'use strict';

// [INIT PRE-SERVER REQUIREMENTS]
var fs = require('fs');
var os = require('os');
var https = require('https');


var swagger = require('swagger-tools');
var app = require('express')();
var db = require(/* db config path */);
var swaggerObject = require('./api/swagger/swagger.json');

// Configure non-Swagger related middleware and server components prior to Swagger middleware

swagger.initializeMiddleware(swaggerObject, function (middleware) {

  // Intialize middleware
  app.use(middleware.swaggerMetadata());

  // Setup security handlers
  app.use(middleware.swaggerSecurity({
    api_key: function(req, def, scopes, callback) {
      // API KEY LOGIC HERE
      // IF SUCCESSFUL
      callback();
    }
  });

  // Route requests to appropriate controller
  app.use(middleware.swaggerRouter({useStubs: true, controllers: './api/controllers'}));

  // Setup documentation
  app.use(middleware.swaggerUi());

  // Start the server
  var httpsServer = https.createServer({
    // KEY INFO
  }, app);
  httpsServer.listen(443, function() {
    console.log('Server created and listening for requests on port 443.');
  });
});