跳至内容

API 密钥

一些 API 使用 API 密钥进行授权。API 密钥是客户端在进行 API 调用时提供的令牌。该密钥可以在查询字符串中发送

1
GET /something?api_key=abcdef12345

或作为请求头

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

或作为 cookie

1
GET /something HTTP/1.1
2
Cookie: X-API-KEY=abcdef12345

API 密钥应该是只有客户端和服务器知道的秘密。与 基本身份验证一样,基于 API 密钥的身份验证只有在与其他安全机制(如 HTTPS/SSL)一起使用时才被认为是安全的。

描述 API 密钥

在 OpenAPI 3.0 中,API 密钥的描述如下

1
openapi: 3.0.0
2
---
3
# 1) Define the key name and location
4
components:
5
securitySchemes:
6
ApiKeyAuth: # arbitrary name for the security scheme
7
type: apiKey
8
in: header # can be "header", "query" or "cookie"
9
name: X-API-KEY # name of the header, query parameter or cookie
10
11
# 2) Apply the API key globally to all operations
12
security:
13
- ApiKeyAuth: [] # use the same name as under securitySchemes

此示例定义了一个名为 X-API-Key 的 API 密钥,作为请求头 X-API-Key: <key> 发送。密钥名称 ApiKeyAuth 是安全方案的任意名称(不要与 API 密钥名称混淆,API 密钥名称由 name 键指定)。名称 ApiKeyAuthsecurity 部分再次使用,以将此安全方案应用于 API。注意:securitySchemes 部分是不够的;您还必须使用 security 才能使 API 密钥生效。security 也可以在操作级别而不是全局设置。如果只有一部分操作需要 API 密钥,则此方法很有用

1
paths:
2
/something:
3
get:
4
# Operation-specific security:
5
security:
6
- ApiKeyAuth: []
7
responses:
8
"200":
9
description: OK (successfully authenticated)

请注意,可以在 API 中支持多种授权类型。请参阅使用多种身份验证类型

多个 API 密钥

一些 API 使用一对安全密钥,例如 API 密钥和 App ID。要指定这些密钥一起使用(如逻辑 AND),请在 security 数组的同一数组项中列出它们

1
components:
2
securitySchemes:
3
apiKey:
4
type: apiKey
5
in: header
6
name: X-API-KEY
7
appId:
8
type: apiKey
9
in: header
10
name: X-APP-ID
11
12
security:
13
- apiKey: []
14
appId: [] # <-- no leading dash (-)

请注意与以下内容的区别

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

这意味着可以使用任何一个密钥(如逻辑 OR)。有关更多示例,请参阅使用多种身份验证类型

401 响应

您可以定义由于缺少或无效的 API 密钥而返回的 401“未授权”响应。此响应包括 WWW-Authenticate 标头,您可能需要提及。与其他常见响应一样,401 响应可以在全局 components/responses 部分中定义,并通过 $ref 在其他地方引用。

1
paths:
2
/something:
3
get:
4
...
5
responses:
6
...
7
'401':
8
$ref: "#/components/responses/UnauthorizedError"
9
post:
10
...
11
responses:
12
...
13
'401':
14
$ref: "#/components/responses/UnauthorizedError"
15
16
components:
17
responses:
18
UnauthorizedError:
19
description: API key is missing or invalid
20
headers:
21
WWW_Authenticate:
22
schema:
23
type: string

要了解有关描述响应的更多信息,请参阅描述响应

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