HTTP cookie

2019-01-06  本文已影响0人  庞贝船长

一个 HTTP cookie 是服务端传给客户端浏览器的一小部分数据,可为无状态的HTTP协议提供前后请求间的上下文会话。cookie 由客户端保存。

Creating cookies

当服务端接收到一个HTTP请求时,可以设置响应报文头部字段 Set-Cookie 字段来生成 cookie。 以后客户端便会在请求报文头部字段 Cookie 中带上上次服务端的 cookie 信息进行请求。

举个栗子:
某次响应报文:

HTTP/2.0 200 OK
Content-type: text/html
Set-Cookie: yummy_cookie=choco
Set-Cookie: tasty_cookie=strawberry

[page content]

下次请求报文:

GET /sample_page.html HTTP/2.0
Host: www.example.org
Cookie: yummy_cookie=choco; tasty_cookie=strawberry

Cookies 存活时间

session cookies

当客户端关闭后,session cookie 便被删除。

permanent cookies

可以通过在响应报文头字段 Set-cookie 中设置 ExpiresMax-Age 来控制 cookies 的存活时间。

Set-Cookie: id=a3fWa; Expires=Wed, 21 Oct 2015 07:28:00 GMT;

XSS and CSRF

拓展

Web storage API

Cookies were once used for general client-side storage. While this was legitimate when they were the only way to store data on the client, it is recommended nowadays to prefer modern storage APIs. Cookies are sent with every request, so they can worsen performance (especially for mobile data connections). Modern APIs for client storage are the Web storage API(localStorage and sessionStorage) and IndexedDB.

参考

上一篇 下一篇

猜你喜欢

热点阅读