浏览器cookie和session:
关于cookie的设置问题:
1>后端symfony7
// 创建 Cookie 对象
$cookie = Cookie::create('user_tt_token')
->withValue('fdsfssdfsdfsdfsdfsdf')
->withExpires(strtotime('tomorrow'))
->withPath('/')
->withDomain('localhost') // 设置域名
->withSecure(false) // 是否仅在 HTTPS 下传输
->withHttpOnly(false) // 是否禁止 JavaScript 访问
->withSameSite('lax');
// $response 为一个jsonResponse对象
$response->headers->setCookie($cookie);
2>前端是一个 nuxt3的SSR的 get 请求
try {
let res = await $fetch<SessionTermDetailResponse>.raw(
`/api/admin/events/${id}/event-session/term`,
{
headers: {
"X-SCIFORUM-API-TOKEN": config.sciforum.apiToken,
"X-Switch-User": event.headers.get("X-Switch-User") ?? "",
authorization: event.headers.get("authorization") ?? "",
},
baseURL: config.sciforum.apiBaseUrl,
}
);
let cc = getCookie(event, "user_tt_token")
console.log("cc is:", cc)
return res;
} catch (error: any) {
return errorHandler(error);
}
经测试,当 sameSite为lax,同时请求为 get 的时候,可以成功将cookie设置到浏览器, 但是实际上需要跨域设置cookie的时候,这种方式是不行的,需要如下修改
// 创建 Cookie 对象
$cookie = Cookie::create('user_tt_token')
->withValue('fdsfssdfsdfsdfsdfsdf')
->withExpires(strtotime('tomorrow'))
->withPath('/')
->withDomain('localhost') // 设置域名
->withSecure(true) // 是否仅在 HTTPS 下传输
->withHttpOnly(false) // 是否禁止 JavaScript 访问
->withSameSite('none');
// $response 为一个jsonResponse对象
$response->headers->setCookie($cookie);
即 SameSite 为 none, 同时 Secure 为 true,但是这个需要 https 环境,目前还没有测试. 看了其它的网站,都是这么处理的,这也可以叫允许三方网站cookie。
还有需要注意的是
1> $fetch 请求,需要 raw 请求,这样才能有 cookie 相关的response。
2>如果在不指定 expires 或 maxAge 时,浏览器会自动将其视为一个 Session Cookie。这类 Cookie 的生命周期仅限于当前的浏览器会话。当用户关闭浏览器后,Session Cookie 会被移除。也就是说cookie按照过期时间可以分为两类:
Session Cookie:如果未设置 expires 或 maxAge 属性,浏览器会将该 Cookie 当作 Session Cookie。这类 Cookie 的生命周期仅限于当前的浏览器会话。当用户关闭浏览器后,Session Cookie 会被移除。
持久性 Cookie:如果设置了 expires(指定过期日期)或 maxAge(指定从当前时间起的秒数),则 Cookie 会在指定的时间之后过期,无论浏览器会话是否仍在进行。
何时使用 Session Cookie
Session Cookie 常用于敏感信息(如登录会话),因为当用户关闭浏览器时,数据会被自动清除,从而提供额外的安全性。
何时使用持久性 Cookie
如果您希望用户在关闭浏览器后保持登录状态,或希望保存某些偏好设置,您可以使用持久性 Cookie,并为其设置具体的过期时间。
