我正在尝试为需要 HMAC-SHA256 身份验证的 API 路由生成 OpenAPI (Swagger) 文档。这意味着我必须包含 Authorization
每个请求的 header ,由 API key 和生成的 HMAC 签名组成,以冒号分隔(例如 Authorization: API_KEY:GENERATED_SIGNATURE
)。
我可以使用 JavaScript 轻松生成所需的签名,但我不知道如何在 Swagger-UI“授权”弹出窗口中添加“ key ”和“ secret ”输入字段以及如何最终将其添加到 Authorization
每个请求中的 header 。
OpenAPI 规范 v3 是否有可能实现这样的事情?
最佳答案
我不会在 Open API Specs 中发布任何可能导致安全问题的 key 和/或 secret 。此类信息应与 API 文档分开并通过安全线路进行交流。
我没有找到很多示例来说明如何至少启用 apiKey,因此这里是定义 HMAC 安全性或 apiKey 的一种方法。 (使用开放 API 规范 3.0)
在 下的根级别组件 , '安全方案 ' 需要定义。 (这是使它正常工作所必需的。)
components:
securitySchemes:
api_key:
type: apiKey
name: gpa_key
in: header
description: HMAC code encoded with key
parameters:
CustomerIdPathParam:
name: customerId
in: query
description: Customer id
required: true
schema:
type: string
maxLength: 32
example: TEST_123012
schemas:
InventoryDetails:
type: objectBlockquote
字段名‘ api_key ' 在 securitySchemes 中必须匹配用于端点定义的安全性。注意:‘ 类型 ' 必须是以下类型之一:“apiKey”、“http”、“oauth2”、“OpenIdConnect”。我选择了 apiKey 在这种情况下代表 HMAC 安全。
然后,您有几种方法可以为您的 API 实现安全性。
info:
servers:
- url: 'https://stage.com'
description: Stage Server
- url: 'https://prod.com'
description: Prod Server
security:
- api_key: [ ]
paths:
/coffee/hot/:
post:
summary: Coffee request order
description: Coffee a request order
security:
- api_key: [ ]
tags:
- Starbuckin
在本例中,我们启用了“” api_key ' 此 POST 请求端点的安全类型。 /coffee/buildinfo:
get:
summary: Show the build information
description: Show the detail build information
tags:
- Starbuckin
security: [ ]
responses:
最后,结果应该在启用了安全性的请求上显示一个安全锁图标。
关于javascript - 在 OpenAPI (Swagger) 中使用 HMAC-SHA256 身份验证测试 API 路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44633370/