跳至內容

基本身份驗證

基本身份驗證是內建於 HTTP 協定中的簡單身份驗證方案。用戶端會傳送 HTTP 請求,其中包含 Authorization 標頭,該標頭包含 Basic 單字,後接一個空格和 base64 編碼的字串 username:password。例如,若要以 demo / p@55w0rd 的身分授權,用戶端會傳送

1
Authorization: Basic ZGVtbzpwQDU1dzByZA==

注意:由於 base64 很容易解碼,因此基本身份驗證應僅與其他安全機制(例如 HTTPS/SSL)一起使用。

描述基本身份驗證

使用 OpenAPI 3.0,您可以如下描述基本身份驗證

1
openapi: 3.0.0
2
---
3
components:
4
securitySchemes:
5
basicAuth: # <-- arbitrary name for the security scheme
6
type: http
7
scheme: basic
8
9
security:
10
- basicAuth: [] # <-- use the same name here

第一個區段 securitySchemes 定義一個名為 basicAuth 的安全性方案(任意名稱)。此方案必須具有 type: httpscheme: basicsecurity 區段接著將基本身份驗證套用至整個 API。方括號 [] 表示使用的安全性範圍;清單為空,因為基本身份驗證不使用範圍。security 可以全域設定(如以上範例所示)或在操作層級設定。如果只有一部分操作需要基本身份驗證,則後者會很有用

1
paths:
2
/something:
3
get:
4
security:
5
- basicAuth: []

基本身份驗證也可以與其他身份驗證方法結合使用,如使用多種身份驗證類型中所述。

401 回應

您也可以定義因請求遺失或不正確的認證而傳回的 401 「未經授權」回應。此回應包括 WWW-Authenticate 標頭,您可能會想要提及。與其他常見回應一樣,401 回應可以在全域 components/responses 區段中定義,並透過 $ref 在其他地方參考。

1
paths:
2
/something:
3
get:
4
...
5
responses:
6
...
7
'401':
8
$ref: '#/components/responses/UnauthorizedError'
9
post:
10
...
11
responses:
12
...
13
'401':
14
$ref: '#/components/responses/UnauthorizedError'
15
...
16
components:
17
responses:
18
UnauthorizedError:
19
description: Authentication information is missing or invalid
20
headers:
21
WWW_Authenticate:
22
schema:
23
type: string

若要深入瞭解 responses 語法,請參閱描述回應

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