Cookie 驗證
Cookie 驗證使用 HTTP Cookie 來驗證用戶端請求並維護工作階段資訊。其運作方式如下
- 用戶端向伺服器傳送登入請求。
- 登入成功後,伺服器回應會包含 Set-Cookie 標頭,其中包含 Cookie 名稱、值、到期時間和其他資訊。以下是一個範例,設定名為
JSESSIONID
的 Cookie
1Set-Cookie: JSESSIONID=abcde12345; Path=/; HttpOnly
- 用戶端需要在後續所有傳送至伺服器的請求中的
Cookie
標頭中傳送此 Cookie。
1Cookie: JSESSIONID=abcde12345
- 在登出作業中,伺服器會傳回
Set-Cookie
標頭,使 Cookie 過期。
注意: Cookie 驗證容易遭受跨網站請求偽造 (CSRF) 攻擊,因此應與其他安全措施(例如 CSRF 權杖)一起使用。
給 Swagger UI 和 Swagger Editor 使用者的注意:由於瀏覽器安全限制,目前不支援「試試看」請求的 Cookie 驗證。如需更多資訊,請參閱此問題。 SwaggerHub 沒有此限制。
描述 Cookie 驗證
在 OpenAPI 3.0 條款中,Cookie 驗證是 API 金鑰,以 in: cookie
傳送。例如,透過名為 JSESSIONID
的 Cookie 進行驗證,定義如下
1openapi: 3.0.02---3# 1) Define the cookie name4components:5 securitySchemes:6 cookieAuth: # arbitrary name for the security scheme; will be used in the "security" key later7 type: apiKey8 in: cookie9 name: JSESSIONID # cookie name10
11# 2) Apply cookie auth globally to all operations12security:13 - cookieAuth: []
在此範例中,Cookie 驗證使用規格根層級的 security
金鑰全域套用至整個 API。如果只有一部分作業需要 Cookie,請在作業層級上套用 security
,而不是全域套用
1paths:2 /users:3 get:4 security:5 - cookieAuth: []6 description: Returns a list of users.7 responses:8 "200":9 description: OK
Cookie 驗證可以與其他驗證方法合併使用,如使用多種驗證類型中所述。
描述 Set-Cookie 標頭
您可能還想記錄您的登入作業會在 Set-Cookie
標頭中傳回 Cookie。您可以將此資訊包含在 description
中,也可以在回應的 headers
中定義 Set-Cookie
標頭,如下所示
1paths:2 /login:3 post:4 summary: Logs in and returns the authentication cookie5 requestBody:6 required: true7 description: A JSON object containing the login and password.8 content:9 application/json:10 schema:11 $ref: "#/components/schemas/LoginRequest"12 security: [] # no authentication13 responses:14 "200":15 description: >16 Successfully authenticated.17 The session ID is returned in a cookie named `JSESSIONID`. You need to include this cookie in subsequent requests.18 headers:19 Set-Cookie:20 schema:21 type: string22 example: JSESSIONID=abcde12345; Path=/; HttpOnly
請注意,Set-Cookie
標頭和 securitySchemes
沒有任何關聯,而且 Set-Header
定義僅供文件用途。