跳至內容

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: headerin: 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 金鑰和應用程式 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

找不到您要的內容嗎?詢問社群
發現錯誤嗎?讓我們知道