跳到内容

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 编辑器用户的注意事项:由于浏览器安全限制,目前“试用”请求不支持 Cookie 身份验证。有关更多信息,请参阅 此问题SwaggerHub 没有此限制。

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

1
openapi: 3.0.0
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 定义仅用于文档目的。

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