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 编辑器用户的注意事项:由于浏览器安全限制,目前“试用”请求不支持 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
定义仅用于文档目的。