跳到内容

API 密钥

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

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

或作为查询参数发送

1
GET /something?api_key=abcdef12345

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

要定义基于 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

没有找到您要找的内容?咨询社区
发现错误?请告知我们