跳至內容

基本身分驗證

基本身分驗證是一種非常簡單的身分驗證方案,內建於 HTTP 通訊協定中。用戶端會傳送 HTTP 請求,並在 Authorization 標頭中包含 Basic 字詞,後面接著一個空格和 base64 編碼的 username:password 字串。例如,包含 demo / p@55w0rd 認證的標頭將編碼為

1
Authorization: Basic ZGVtbzpwQDU1dzByZA==

注意:因為 base64 很容易解碼,所以基本身分驗證應僅與 HTTPS/SSL 等其他安全性機制一起使用。

基本身分驗證很容易定義。在全域 securityDefinitions 區段中,新增一個具有 type: basic 和任意名稱的項目(在此範例中為 basicAuth)。然後,使用 security 區段將安全性套用至整個 API 或特定作業。

1
securityDefinitions:
2
basicAuth:
3
type: basic
4
5
# To apply Basic auth to the whole API:
6
security:
7
- basicAuth: []
8
9
paths:
10
/something:
11
get:
12
# To apply Basic auth to an individual operation:
13
security:
14
- basicAuth: []
15
responses:
16
200:
17
description: OK (successfully authenticated)

401 回應

您也可以定義針對遺失或不正確認證的請求傳回的 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: Authentication information is missing or invalid
18
headers:
19
WWW_Authenticate:
20
type: string

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