身分驗證
Swagger 2.0 可讓您為 API 定義下列身分驗證類型
請遵循以上連結,取得這些身分驗證類型的特定範例,或繼續閱讀以瞭解如何一般性地描述身分驗證。
身分驗證是使用 securityDefinitions
和 security
關鍵字描述的。您可以使用 securityDefinitions
定義 API 支援的所有身分驗證類型,然後使用 security
將特定的身分驗證類型套用至整個 API 或個別操作。
securityDefinitions
區段用於定義 API 支援的所有安全機制(身分驗證類型)。它是一個名稱->定義對應,將任意名稱對應至安全機制定義。在這裡,API 支援三個名為 BasicAuth、ApiKeyAuth 和 OAuth2 的安全機制,這些名稱將用於從其他地方參照這些安全機制
1securityDefinitions:2 BasicAuth:3 type: basic4 ApiKeyAuth:5 type: apiKey6 in: header7 name: X-API-Key8 OAuth2:9 type: oauth210 flow: accessCode11 authorizationUrl: https://example.com/oauth/authorize12 tokenUrl: https://example.com/oauth/token13 scopes:14 read: Grants read access15 write: Grants write access16 admin: Grants read and write access to administrative information
每個安全機制的 type
可以是
basic
代表基本身分驗證apiKey
代表 API 金鑰oauth2
代表 OAuth 2
其他必要的屬性取決於安全類型。如需詳細資訊,請查看Swagger 規範或我們的基本身分驗證和API 金鑰範例。
在 securityDefinitions
中定義安全機制後,您可以分別將 security
區段新增至根層級或操作層級,將其套用至整個 API 或個別操作。在根層級使用時,security
會將指定的安全機制全域套用至所有 API 操作,除非在操作層級覆寫。
在以下範例中,可以使用 API 金鑰或 OAuth 2 驗證 API 呼叫。ApiKeyAuth 和 OAuth2 名稱是指先前在 securityDefinitions
中定義的安全機制。
1security:2 - ApiKeyAuth: []3 - OAuth2: [read, write]
全域 security
可以在個別操作中覆寫,以使用不同的身分驗證類型、不同的 OAuth 2 範圍,或完全不使用身分驗證
1paths:2/billing_info:3 get:4 summary: Gets the account billing info5 security:6 - OAuth2: [admin] # Use OAuth with a different scope7 responses:8 200:9 description: OK10 401:11 description: Not authenticated12 403:13 description: Access token does not have the required scope14
15/ping:16 get:17 summary: Checks if the server is running18 security: [] # No security19 responses:20 200:21 description: Server is up and running22 default:23 description: Something is wrong
使用多種身分驗證類型
某些 REST API 支援多種身分驗證類型。security
區段可讓您使用邏輯 OR 和 AND 組合安全性需求,以達到預期的結果。security
使用以下邏輯
1security: # A OR B2 - A3 - B4
5security: # A AND B6 - A7 B8
9security: # (A AND B) OR (C AND D)10 - A11 B12 - C13 D
也就是說,security
是雜湊圖的陣列,其中每個雜湊圖包含一個或多個具名的安全機制。雜湊圖中的項目使用邏輯 AND 組合,陣列項目使用邏輯 OR 組合。透過 OR 組合的安全機制是替代方案 – 在給定的內容中可以使用任何一個。透過 AND 組合的安全機制必須在同一個請求中同時使用。在這裡,我們可以使用基本身分驗證或 API 金鑰
1security:2 - basicAuth: []3 - apiKey: []
在這裡,API 要求在請求中包含一對 API 金鑰
1security:2 - apiKey1: []3 apiKey2: []
在這裡,我們可以使用 OAuth 2 或一對 API 金鑰
1security:2 - oauth2: [scope1, scope2]3 - apiKey1: []4 apiKey2: []
常見問題
在 「securitySchemeName: [ ]」 中,[ ] 代表什麼意思?
[]
是 YAML/JSON 的空陣列語法。Swagger 規範要求 security
陣列中的項目指定必要範圍的清單,如下所示
1security:2 - securityA: [scopeA1, scopeA2]3 - securityB: [scopeB1, scopeB2]
範圍僅與 OAuth 2 一起使用,因此基本和 API 金鑰 security
項目會改用空陣列。
1security:2 - oauth2: [scope1, scope2]3 - BasicAuth: []4 - ApiKeyAuth: []