跳到内容

API 密钥

有些 API 使用 API 密钥进行授权。API 密钥是客户端在进行 API 调用时需要提供的一种特殊令牌。该密钥通常作为请求头发送

1
GET /something HTTP/1.1
2
X-API-Key: abcdef12345

或作为查询参数

1
GET /something?api_key=abcdef12345

API 密钥应是只有客户端和服务器知道的秘密。但是,与基本认证一样,基于 API 密钥的认证除非与 HTTPS/SSL 等其他安全机制一起使用,否则不被认为是安全的。

定义基于 API 密钥的安全性

  • 在全局 securityDefinitions 部分添加一个带有 type: apiKey 的条目。条目名称可以是任意的(例如下面示例中的 APIKeyHeader),并用于从规范的其他部分引用此安全定义。
  • 指定 API 密钥将通过 in: header 还是 in: query 传递。
  • 为该参数或请求头指定一个 name
1
securityDefinitions:
2
# X-API-Key: abcdef12345
3
APIKeyHeader:
4
type: apiKey
5
in: header
6
name: X-API-Key
7
# /path?api_key=abcdef12345
8
APIKeyQueryParam:
9
type: apiKey
10
in: query
11
name: api_key

然后,在根级别或操作级别使用 security 部分,将 API 密钥应用于整个 API 或特定操作。

1
# Global security (applies to all operations):
2
security:
3
- APIKeyHeader: []
4
paths:
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 数组的同一数组项中

1
securityDefinitions:
2
apiKey:
3
type: apiKey
4
in: header
5
name: X-API-KEY
6
appId:
7
type: apiKey
8
in: header
9
name: X-APP-ID
10
security:
11
- apiKey: []
12
appId: []

注意与以下内容的区别

1
security:
2
- apiKey: []
3
- appId: []

这意味着可以使用任一密钥(如逻辑 OR)。更多示例请参见 使用多种认证类型

401 响应

您还可以定义因缺少或无效 API 密钥而返回的 401“未经授权”响应。此响应包含 WWW-Authenticate 请求头,您可能希望提及它。与其他常见响应一样,401 响应可以在全局 responses 部分中定义,并从多个操作中引用。

1
paths:
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'
15
responses:
16
UnauthorizedError:
17
description: API key is missing or invalid
18
headers:
19
WWW_Authenticate:
20
type: string

没有找到您想要的内容? 向社区提问
发现错误? 告诉我们

© . All rights reserved.