跳至內容

身分驗證

Swagger 2.0 可讓您為 API 定義下列身分驗證類型

  • 基本身分驗證
  • API 金鑰(作為標頭或查詢字串參數)
  • OAuth 2 常見流程(授權碼、隱式、資源擁有者密碼憑證、用戶端憑證)

請遵循以上連結,取得這些身分驗證類型的特定範例,或繼續閱讀以瞭解如何一般性地描述身分驗證。

身分驗證是使用 securityDefinitionssecurity 關鍵字描述的。您可以使用 securityDefinitions 定義 API 支援的所有身分驗證類型,然後使用 security 將特定的身分驗證類型套用至整個 API 或個別操作。

securityDefinitions 區段用於定義 API 支援的所有安全機制(身分驗證類型)。它是一個名稱->定義對應,將任意名稱對應至安全機制定義。在這裡,API 支援三個名為 BasicAuthApiKeyAuthOAuth2 的安全機制,這些名稱將用於從其他地方參照這些安全機制

1
securityDefinitions:
2
BasicAuth:
3
type: basic
4
ApiKeyAuth:
5
type: apiKey
6
in: header
7
name: X-API-Key
8
OAuth2:
9
type: oauth2
10
flow: accessCode
11
authorizationUrl: https://example.com/oauth/authorize
12
tokenUrl: https://example.com/oauth/token
13
scopes:
14
read: Grants read access
15
write: Grants write access
16
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 呼叫。ApiKeyAuthOAuth2 名稱是指先前在 securityDefinitions 中定義的安全機制。

1
security:
2
- ApiKeyAuth: []
3
- OAuth2: [read, write]

全域 security 可以在個別操作中覆寫,以使用不同的身分驗證類型、不同的 OAuth 2 範圍,或完全不使用身分驗證

1
paths:
2
/billing_info:
3
get:
4
summary: Gets the account billing info
5
security:
6
- OAuth2: [admin] # Use OAuth with a different scope
7
responses:
8
200:
9
description: OK
10
401:
11
description: Not authenticated
12
403:
13
description: Access token does not have the required scope
14
15
/ping:
16
get:
17
summary: Checks if the server is running
18
security: [] # No security
19
responses:
20
200:
21
description: Server is up and running
22
default:
23
description: Something is wrong

使用多種身分驗證類型

某些 REST API 支援多種身分驗證類型。security 區段可讓您使用邏輯 OR 和 AND 組合安全性需求,以達到預期的結果。security 使用以下邏輯

1
security: # A OR B
2
- A
3
- B
4
5
security: # A AND B
6
- A
7
B
8
9
security: # (A AND B) OR (C AND D)
10
- A
11
B
12
- C
13
D

也就是說,security 是雜湊圖的陣列,其中每個雜湊圖包含一個或多個具名的安全機制。雜湊圖中的項目使用邏輯 AND 組合,陣列項目使用邏輯 OR 組合。透過 OR 組合的安全機制是替代方案 – 在給定的內容中可以使用任何一個。透過 AND 組合的安全機制必須在同一個請求中同時使用。在這裡,我們可以使用基本身分驗證或 API 金鑰

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

在這裡,API 要求在請求中包含一對 API 金鑰

1
security:
2
- apiKey1: []
3
apiKey2: []

在這裡,我們可以使用 OAuth 2 或一對 API 金鑰

1
security:
2
- oauth2: [scope1, scope2]
3
- apiKey1: []
4
apiKey2: []

常見問題

「securitySchemeName: [ ]」 中,[ ] 代表什麼意思?

[] 是 YAML/JSON 的空陣列語法。Swagger 規範要求 security 陣列中的項目指定必要範圍的清單,如下所示

1
security:
2
- securityA: [scopeA1, scopeA2]
3
- securityB: [scopeB1, scopeB2]

範圍僅與 OAuth 2 一起使用,因此基本和 API 金鑰 security 項目會改用空陣列。

1
security:
2
- oauth2: [scope1, scope2]
3
- BasicAuth: []
4
- ApiKeyAuth: []

參考資料

securityDefinitions

security

找不到您要找的內容嗎?詢問社群
發現錯誤了嗎?請告訴我們