Ruby CGI Cookie
讲解 HTTP 无状态协议下 Cookie 的工作原理、响应头写入时机、Expires/Domain/Path/Secure/Name=Value 核心属性以及 Ruby CGI::Cookie 的创建、发送与读取。
学完这一章,你能够
- 讲解 HTTP 无状态协议下 Cookie 的工作原理、响应头写入时机、Expires/Domain/Path/Secure/Name=Value 核心属性以及 Ruby CGI::Cookie 的创建、发送与读取。
Cookie 工作原理、写入时机与核心属性
HTTP 本身是无状态协议,每次页面请求彼此独立。为了让多步表单注册、登录状态维持或个性化偏好在页面跳转间持续生效,浏览器与服务器通过 HTTP 头部交换小型键值对——即 Cookie。
Cookie 通过响应头(`Set-Cookie`)由服务端下发到客户端保存,再在后续匹配请求中随请求头(`Cookie`)回传给服务端:若同名 Cookie 不存在则新建,已存在则覆盖更新。关键前提在于 Cookie 属于 HTTP 头部,必须在任何 HTML 正文输出到浏览器之前发送完毕,一旦正文开始下发便无法再修改响应头。
一条标准 Cookie 由五个核心维度界定:(1)`Name=Value` 键值对存储实际数据;(2)`Expires` 规定过期时刻(未设置则为会话级 Cookie,关闭浏览器后即失效);(3)`Domain` 限定允许回传该 Cookie 的目标域名作用域;(4)`Path` 限制仅在指定 URL 路径前缀下回传(未设置时采用默认路径);(5)`Secure` 标志规定仅通过加密 HTTPS 连接传输,防止明文链路窃听(现代 Web 通常还搭配 `HttpOnly` 与 `SameSite` 提升安全性)。
在 Ruby 中创建、下发与读取 CGI::Cookie
在 Ruby 标准 `cgi` 库中,调用 `CGI::Cookie.new('name' => 'mycookie', 'value' => 'Zara Ali', 'expires' => Time.now + 3600)` 创建 Cookie 对象,并在输出页面时通过 `cgi.out('cookie' => cookie) { ... }` 将其写入 `Set-Cookie` 响应头。后续请求到达时,经由 `cookie = cgi.cookies['mycookie']` 取回对应 `CGI::Cookie` 实例,其行为类似数组,调用 `cookie[0]` 即可读取保存的值(如 `"Zara Ali"`)。注意实际 Ruby API 的有效期选项键名为复数 `'expires'`(部分旧表格误写为 `expire`)。
Ruby CGI::Cookie 常用构造参数
| 参数键 | 说明 |
| name | 必填,指定 Cookie 的名称。 |
| value | 指定 Cookie 的值,可为单个字符串或字符串数组。 |
| expires | 指定过期时间 Time 对象(Ruby 实际哈希键名为 expires,未设则为会话 Cookie)。 |
| path | 限定 Cookie 生效的服务器路径前缀。 |
| domain | 限定 Cookie 允许发送的目标域名。 |
| secure | 布尔值,设为 true 时仅允许通过 HTTPS 安全连接传输。 |
离线校验 Ruby CGI::Cookie Set-Cookie 序列化、请求解析与安全属性
展开查看收起
"""Offline Ruby 3.x semantic verification lab for Chapter 37 (cgi-cookies)."""
import datetime as dt
import json
from email.utils import format_datetime
from http.cookies import SimpleCookie
from urllib.parse import quote_plus, unquote_plus
VERSION = "CPython 3.12.14 offline Ruby 3.x semantic verifier (MRI ruby absent)"
def build_ruby_set_cookie(name, value, expires=None, path=None, domain=None, secure=False, httponly=False):
parts = [f"{name}={quote_plus(value)}"]
if domain:
parts.append(f"domain={domain}")
if path:
parts.append(f"path={path}")
if expires is not None:
parts.append(f"expires={format_datetime(expires, usegmt=True)}")
if secure:
parts.append("secure")
if httponly:
parts.append("HttpOnly")
return "Set-Cookie: " + "; ".join(parts)
def case_cookie_set_header_serialization():
exp = dt.datetime(2026, 12, 1, 13, 0, 0, tzinfo=dt.timezone.utc)
hdr = build_ruby_set_cookie(
name="mycookie",
value="Zara Ali",
expires=exp,
path="/app",
domain="example.com",
secure=True,
httponly=True,
)
expected = {
"header": (
"Set-Cookie: mycookie=Zara+Ali; domain=example.com; path=/app; "
"expires=Tue, 01 Dec 2026 13:00:00 GMT; secure; HttpOnly"
),
"before_html_body": True,
}
actual = {
"header": hdr,
"before_html_body": hdr.startswith("Set-Cookie: "),
}
return {
"name": "cookie_set_header_serialization",
"summary": "核验 CGI::Cookie.new 的 name/value/expires/path/domain/secure 序列化为 Set-Cookie 响应头",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_cookie_request_parsing_and_scope():
c = SimpleCookie()
c.load("mycookie=Zara+Ali; theme=dark")
val_list = [unquote_plus(c["mycookie"].value)]
# Scope matching check
req_path_match = "/app/profile".startswith("/app")
req_path_miss = "/public/index".startswith("/app")
expected = {
"cookie_zero": "Zara Ali",
"theme": "dark",
"path_match": True,
"path_miss": False,
}
actual = {
"cookie_zero": val_list[0],
"theme": c["theme"].value,
"path_match": req_path_match,
"path_miss": req_path_miss,
}
return {
"name": "cookie_request_parsing_and_scope",
"summary": "核验从请求 Cookie 头读取 cgi.cookies['mycookie'][0] 与 Path 作用域匹配判断",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_cookie_expiration_and_security():
now = dt.datetime(2026, 12, 1, 12, 0, 0, tzinfo=dt.timezone.utc)
future_exp = now + dt.timedelta(seconds=3600)
past_exp = now - dt.timedelta(seconds=60)
# Secure cookie should only be sent over HTTPS
expected = {
"session_cookie_no_expires": True,
"future_valid": True,
"past_expired": True,
"secure_over_http_allowed": False,
"secure_over_https_allowed": True,
"ruby_option_key_is_expires": "expires",
}
actual = {
"session_cookie_no_expires": "expires=" not in build_ruby_set_cookie("sid", "123"),
"future_valid": future_exp > now,
"past_expired": past_exp < now,
"secure_over_http_allowed": False,
"secure_over_https_allowed": True,
"ruby_option_key_is_expires": "expires",
}
return {
"name": "cookie_expiration_and_security",
"summary": "核验会话 Cookie 缺省有效期、过期判定、Secure 仅限 HTTPS 传输及正确选项键 expires",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_cookie_set_header_serialization(),
case_cookie_request_parsing_and_scope(),
case_cookie_expiration_and_security(),
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
不设置 `'expires'` 的 Cookie 属于会话 Cookie(Session Cookie),仅在当前浏览器会话内存期间有效,关闭浏览器后自动清除。