API 金鑰
有些 API 使用 API 金鑰進行授權。API 金鑰是客戶端在進行 API 呼叫時需要提供的特殊權杖。金鑰通常會作為請求標頭傳送
1GET /something HTTP/1.12X-API-Key: abcdef12345
或作為查詢參數傳送
1GET /something?api_key=abcdef12345
API 金鑰應是只有客戶端和伺服器知道的機密。但是,如同基本驗證,除非與其他安全機制 (例如 HTTPS/SSL) 一起使用,否則基於 API 金鑰的驗證並不被視為安全。
若要定義基於 API 金鑰的安全性
- 在全域
securityDefinitions
區段中新增一個具有type: apiKey
的項目。項目名稱可以是任意的 (例如,以下範例中的 APIKeyHeader),並用於從規格的其他部分參照此安全性定義。 - 指定 API 金鑰將以
in: header
或in: query
的方式傳遞。 - 為該參數或標頭指定一個
name
。
1securityDefinitions:2 # X-API-Key: abcdef123453 APIKeyHeader:4 type: apiKey5 in: header6 name: X-API-Key7 # /path?api_key=abcdef123458 APIKeyQueryParam:9 type: apiKey10 in: query11 name: api_key
然後,在根層級或操作層級使用 security
區段,將 API 金鑰套用至整個 API 或特定操作。
1# Global security (applies to all operations):2security:3 - APIKeyHeader: []4paths: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
陣列中的同一個陣列項目中列出它們
1securityDefinitions:2 apiKey:3 type: apiKey4 in: header5 name: X-API-KEY6 appId:7 type: apiKey8 in: header9 name: X-APP-ID10security:11 - apiKey: []12 appId: []
請注意與
1security:2 - apiKey: []3 - appId: []
的區別,後者表示可以使用任何一個金鑰 (如邏輯 OR)。如需更多範例,請參閱使用多種驗證類型。
401 回應
您也可以定義針對遺失或無效 API 金鑰的請求傳回的 401「未授權」回應。此回應包含 WWW-Authenticate
標頭,您可能想要提及。如同其他常見回應,401 回應可以在全域 responses
區段中定義,並從多個操作參照。
1paths: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'15responses:16 UnauthorizedError:17 description: API key is missing or invalid18 headers:19 WWW_Authenticate:20 type: string