API 密钥
有些 API 使用 API 密钥进行授权。API 密钥是客户端在进行 API 调用时需要提供的一种特殊令牌。该密钥通常作为请求头发送
1GET /something HTTP/1.12X-API-Key: abcdef12345
或作为查询参数
1GET /something?api_key=abcdef12345
API 密钥应是只有客户端和服务器知道的秘密。但是,与基本认证一样,基于 API 密钥的认证除非与 HTTPS/SSL 等其他安全机制一起使用,否则不被认为是安全的。
定义基于 API 密钥的安全性
- 在全局
securityDefinitions
部分添加一个带有type: apiKey
的条目。条目名称可以是任意的(例如下面示例中的 APIKeyHeader),并用于从规范的其他部分引用此安全定义。 - 指定 API 密钥将通过
in: header
还是in: query
传递。 - 为该参数或请求头指定一个
name
。
1securityDefinitions:2 # X-API-Key: abcdef123453 APIKeyHeader:4 type: apiKey5 in: header6 name: X-API-Key7 # /path?api_key=abcdef123458 APIKeyQueryParam:9 type: apiKey10 in: query11 name: api_key
然后,在根级别或操作级别使用 security
部分,将 API 密钥应用于整个 API 或特定操作。
1# Global security (applies to all operations):2security:3 - APIKeyHeader: []4paths:5 /something:6 get:7 # Operation-specific security:8 security:9 - APIKeyQueryParam: []10 responses:11 200:12 description: OK (successfully authenticated)
请注意,API 中可能支持多种认证类型。请参阅 使用多种认证类型。
一对 API 密钥
有些 API 使用一对安全密钥,例如 API 密钥和 App ID。要指定这些密钥是同时使用的(如逻辑 AND),请将它们列在 security
数组的同一数组项中
1securityDefinitions:2 apiKey:3 type: apiKey4 in: header5 name: X-API-KEY6 appId:7 type: apiKey8 in: header9 name: X-APP-ID10security:11 - apiKey: []12 appId: []
注意与以下内容的区别
1security:2 - apiKey: []3 - appId: []
这意味着可以使用任一密钥(如逻辑 OR)。更多示例请参见 使用多种认证类型。
401 响应
您还可以定义因缺少或无效 API 密钥而返回的 401“未经授权”响应。此响应包含 WWW-Authenticate
请求头,您可能希望提及它。与其他常见响应一样,401 响应可以在全局 responses
部分中定义,并从多个操作中引用。
1paths:2 /something:3 get:4 ...5 responses:6 ...7 401:8 $ref: '#/responses/UnauthorizedError'9 post:10 ...11 responses:12 ...13 401:14 $ref: '#/responses/UnauthorizedError'15responses:16 UnauthorizedError:17 description: API key is missing or invalid18 headers:19 WWW_Authenticate:20 type: string