【问题标题】:How to put authentication with apiKey in hapi-swagger?如何在 hapi-swagger 中使用 apiKey 进行身份验证?
【发布时间】:2016-02-23 00:14:39
【问题描述】:

我有一个节点项目,我正在使用 hapi 框架以及 joi 和 hapi-swagger。它工作正常并正确生成 API 文档。 现在我需要 http://localhost:5000/documentation url 只有当我提供 apiKey 作为查询参数时才能访问。基本上我想要身份验证,这样没有 apiKey 的人就无法访问 http://localhost:5000/documentation

我试过的代码-

var swaggerOptions = {
  apiVersion: '2.0',
  auth: 'apiKey',
  authorizations: {
    apiKey : {
      type: 'apiKey',
      passAs: 'query',
      keyname: 'secret_password'
    }
  }
}

var server = new Hapi.Server()
server.connection({port: 5000})

server.route(<router>) //router contains all the routes

const scheme = function (server, options) {
  return {
    authenticate: function (request, reply) {
      if (request.query['secret_password'] !== 'XXX') {
        return reply(Boom.unauthorized('credentials failed'))
      }
      return reply.continue({credentials: {user: 'developer'}})
    }
  }
}
server.auth.scheme('custom', scheme)

server.register([inert, vision, {register:hapiSwagger, options:swaggerOptions}], function (err) {
      server.auth.strategy('apiKey', 'custom')
      server.start(callback)
    })

在运行它时,它会在 secret_password 错误时正确显示,但当它正确时,它只会显示一个单词 swagger,指的是 swagger.io 链接。

我进行了搜索,但没有得到任何关于此的信息或示例。 我错过了什么吗?

【问题讨论】:

  • 它是否适用于npm install hapi-swagger@3.0.0-rc1github.com/glennjones/hapi-swagger/issues/180
  • 没有。我尝试使用 3.0.0-rc1 这是我的新 swaggerOptions 对象。 var swaggerOptions = { //apiVersion: '2.0', //auth: 'apiKey', authorizations: [{ apiKey : { type: 'apiKey', passAs: 'query', keyname: 'secret_password' }] } 它抛出 [1] "authorizations" is not allowed 错误。

标签: node.js swagger swagger-ui hapijs


【解决方案1】:

v3.0.0-rc1 中存在一个已知的身份验证问题。此版本是正在开发的新版本的早期候选版本。如果您移回最新的稳定版本 v2.2.3 身份验证应该可以工作。

【讨论】:

  • 我认为你和其他人选择开发版本的原因是 npm publish 没有正确标记。如果这给您带来了问题,我很抱歉。我已更正此问题,但不得不将版本升级到 v2.2.4。请确保您再次阅读 README.md 文件。 hapi-swagger 的选项在 v2.x 和 v3.x 之间是不同的
  • 我尝试使用 v2.2.4 和 v3.0.0-rc1(对选项进行必要的更改),但行为是相同的。是否有任何可用的示例?无法理解我做错了什么。
猜你喜欢
  • 2013-10-06
  • 2020-01-31
  • 1970-01-01
  • 1970-01-01
  • 2021-01-06
  • 2020-07-26
  • 2020-12-21
  • 2018-08-29
  • 1970-01-01
相关资源
最近更新 更多