跳至內容

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 金鑰應該是只有客戶端和伺服器知道的秘密。與 基本驗證一樣,只有與其他安全機制(例如 HTTPS/SSL)一起使用時,基於 API 金鑰的驗證才被認為是安全的。

描述 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

若要深入瞭解如何描述回應,請參閱描述回應

沒有找到您要尋找的內容嗎?向社群提問
發現錯誤?讓我們知道