跳至內容

持票人身分驗證

持票人身分驗證(也稱為權杖身分驗證)是一種 HTTP 身分驗證方案,其中涉及稱為持票人權杖的安全權杖。「持票人身分驗證」的名稱可以理解為「授予此權杖持有者的存取權」。持票人權杖是一個難以理解的字串,通常由伺服器產生以回應登入請求。用戶端在向受保護資源發出請求時,必須在 Authorization 標頭中傳送此權杖

1
Authorization: Bearer <token>

持票人身分驗證方案最初是作為 OAuth 2.0 的一部分在 RFC 6750 中建立,但有時也單獨使用。與 基本身分驗證類似,持票人身分驗證應僅透過 HTTPS (SSL) 使用。

描述持票人身分驗證

在 OpenAPI 3.0 中,持票人身分驗證是具有 type: httpscheme: bearer 的安全性方案。您首先需要在 components/securitySchemes 下定義安全性方案,然後使用 security 關鍵字將此方案套用至所需的範圍 – 全域(如下例所示)或特定操作

1
openapi: 3.0.0
2
---
3
# 1) Define the security scheme type (HTTP bearer)
4
components:
5
securitySchemes:
6
bearerAuth: # arbitrary name for the security scheme
7
type: http
8
scheme: bearer
9
bearerFormat: JWT # optional, arbitrary value for documentation purposes
10
11
# 2) Apply the security globally to all operations
12
security:
13
- bearerAuth: [] # use the same name as above

選用的 bearerFormat 是一個任意字串,用於指定持票人權杖的格式。由於持票人權杖通常由伺服器產生,bearerFormat 主要用於文件目的,作為對用戶端的提示。在上面的範例中,它是「JWT」,表示 JSON Web TokenbearerAuth: [] 中的方括號 [] 包含 API 呼叫所需的安全範圍清單。該清單為空,因為範圍僅與 OAuth 2 和 OpenID Connect 一起使用。在上面的範例中,持票人身分驗證全域套用至整個 API。如果您需要將它套用至少數操作,請在操作層級新增 security,而不是全域執行此操作

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

使用多種身分驗證類型中所述,持票人身分驗證也可以與其他身分驗證方法結合使用。

401 回應

您也可以定義未包含適當持票人權杖的請求所傳回的 401「未經授權」回應。由於 401 回應將由多個操作使用,您可以在全域 components/responses 區段中定義它,並透過 $ref 在其他地方引用。

1
paths:
2
/something:
3
get:
4
...
5
responses:
6
'401':
7
$ref: '#/components/responses/UnauthorizedError'
8
...
9
post:
10
...
11
responses:
12
'401':
13
$ref: '#/components/responses/UnauthorizedError'
14
...
15
16
components:
17
responses:
18
UnauthorizedError:
19
description: Access token is missing or invalid

若要瞭解更多關於 responses 的資訊,請參閱描述回應

找不到您要找的資訊嗎?向社群提問
發現錯誤?讓我們知道