跳到内容

Cookie 身份验证

Cookie 身份验证使用 HTTP cookie 来验证客户端请求并维护会话信息。其工作原理如下:

  1. 客户端向服务器发送登录请求。
  2. 登录成功后,服务器响应包含 Set-Cookie 头,其中包含 cookie 名称、值、过期时间以及其他信息。以下是一个设置名为 JSESSIONID 的 cookie 的示例:
1
Set-Cookie: JSESSIONID=abcde12345; Path=/; HttpOnly
  1. 客户端需要在所有后续请求中将此 cookie 包含在 Cookie 头中发送到服务器。
1
Cookie: JSESSIONID=abcde12345
  1. 在注销操作时,服务器会发送 Set-Cookie 头,导致 cookie 过期。

注意:Cookie 身份验证容易受到跨站请求伪造 (CSRF) 攻击,因此应与其他安全措施(例如 CSRF 令牌)结合使用。

Swagger UI 和 Swagger Editor 用户注意事项:由于浏览器安全限制,当前不支持“试用”请求的 Cookie 身份验证。有关更多信息,请参阅此问题SwaggerHub 没有此限制。

在 OpenAPI 3.0 中,cookie 身份验证是一种 API 密钥,它以 in: cookie 的形式发送。例如,通过名为 JSESSIONID 的 cookie 进行身份验证的定义如下:

1
openapi: 3.0.4
2
---
3
# 1) Define the cookie name
4
components:
5
securitySchemes:
6
cookieAuth: # arbitrary name for the security scheme; will be used in the "security" key later
7
type: apiKey
8
in: cookie
9
name: JSESSIONID # cookie name
10
11
# 2) Apply cookie auth globally to all operations
12
security:
13
- cookieAuth: []

在此示例中,cookie 身份验证通过规范根级别的 security 键全局应用于整个 API。如果只需要对部分操作使用 cookie,则应在操作级别而不是全局应用 security

1
paths:
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 头中返回 cookie。您可以将此信息包含在 description 中,并在响应 headers 中定义 Set-Cookie 头,如下所示:

1
paths:
2
/login:
3
post:
4
summary: Logs in and returns the authentication cookie
5
requestBody:
6
required: true
7
description: A JSON object containing the login and password.
8
content:
9
application/json:
10
schema:
11
$ref: "#/components/schemas/LoginRequest"
12
security: [] # no authentication
13
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: string
22
example: JSESSIONID=abcde12345; Path=/; HttpOnly

请注意,Set-Cookie 头和 securitySchemes 之间没有任何连接,并且 Set-Header 定义仅用于文档目的。

没有找到您要找的内容?向社区提问
发现错误?告诉我们

© . All rights reserved.