This is the first day of my participation in Gwen Challenge

Introduction of cookies

HTTP is a stateless protocol. The protocol itself does not retain information about previous requests or corresponding packets. This reduces server resource consumption, processes a large number of transactions more quickly, ensures the scalability of the protocol, and enables the protocol to be applied to more scenarios.

However, in many scenarios, the server needs to specify which user the request comes from, and expects the client to inform the server of the user’s login status and other information. Therefore, HTTP/1.1 introduces cookies to realize user identification and status information management.

Different browsers have different limits on the number and size of cookies. Generally speaking, a maximum of 30 cookies can be configured for a single domain name, and the size of each Cookie cannot exceed 4KB. After the limit is exceeded, cookies are ignored and will not be set.

Cookies are mainly used for the following three aspects:

  • Session state management (such as user login status, shopping cart, game score, or other information that needs to be logged)
  • Personalization (such as user-defined Settings, themes, etc.)
  • Browser behavior tracking (e.g. tracking and analyzing user behavior, etc.)

HTTP header field for Cookie service:

  • HTTP response. Cookies are configured using the set-cookie field

    HTTP / 1.1 200 OK
    ...
    Set-Cookie: name=LvLin; domain=github.com; path=/blogSet-Cookie: id=test123;
    Copy the code
  • When the browser sends an HTTP request to the server, it automatically carries a Cookie that meets the conditions (see below for details).

    GET /sample_page.html HTTP / 1.1
    Host: www.github.com
    Cookie: name=value; name2=value2; name3=value3
    Copy the code

Document. cookie can be used to return cookies for the current web page or to create new cookies, but Document. cookie cannot create and access cookies with HttpOnly tags.

document.cookie // "name=LvLin; id=test123"

document.cookie = "a=1" // There can be no Spaces on either side of the equals sign
document.cookie // "a=1; name=LvLin; id=test123"
Copy the code

If you want to change an existing Cookie (via set-cookie or document. Cookie), you need to match key, domain, path and secure. Otherwise, two cookies with the same name will appear. The back end is indistinguishable.

This section describes cookie properties

The name and value

Cookie content information is stored in the form of name=value and is case sensitive.

domain

The domain property specifies which domain names should accompany the Cookie when the browser makes an HTTP request.

You can set domain to the domain name of the current server or the parent domain name. If not set, the Cookie value can only be carried in requests to the domain name. If a domain is set, requests to that domain and subdomains take the Cookie with them.

Due to historical reasons, there are domains with prefix dots, which allow subdomain requests to carry this cookie, whereas non-pre-conjugates do not. The current specification ignores prefix points.

path

Path specifies which paths to attach the Cookie to when the browser makes an HTTP request. If path is set during configuration, all subpaths under this path are allowed to carry the cookie.

Expires, the Max – Age

These two fields define the lifetime of the Cookie. Expires is an absolute time. If it is not set or set to null, it indicates a Session Cookie. Note that browsers compare Expires with local time, and local time can change, so there is no guarantee that cookies will expire at the time specified by the server.

Max-age is a relative time, the number of seconds that must pass before the Cookie expires. A number of seconds of 0 or -1 will expire the Cookie directly.

HTTP / 1.1 200 OK
...
Set-Cookie: id=test123; Expires=Tue, 01 Jun 2021 11:45:54 GMT;
Copy the code

If both Expires and max-age are specified, the max-age value takes precedence. If neither is specified, the Cookie is the Session Cookie and will be deleted once the user closes the browser. Some browsers provide Session recovery, in which case the Session Cookie is retained even after the browser is closed, as if the browser was never closed, resulting in the Cookie’s lifetime being extended indefinitely.

SameSite

SameSite cookies prevent cross-site request forgery attacks (CSRF) by allowing the server to request that a Cookie not be sent during a cross-site request. There are three values: Strict, Lax, and None. The default value is None, but the default value is Lax. If it is None, the Secure attribute must be configured.

The Cookie sending situation corresponding to the three rules is as follows:

Request type The instance Strict Lax None
link <a href=”…” ></a> Don’t happen Send a Cookie Send a Cookie
preload <link rel=”prerender” href=”…” /> Don’t send Send a Cookie Send a Cookie
Get the form <form method=”GET” action=”…” > Don’t send Send a Cookie Send a Cookie
Post form <form method=”post” action=”…” > Don’t send Don’t send Send a Cookie
iframe <iframe src=”…” ></iframe> Don’t send Don’t send Send a Cookie
AJAX $.get(“…” ) Don’t send Don’t send Send a Cookie
Image <img src=”…” > Don’t send Don’t send Send a Cookie

Secure, HttpOnly

The Secure attribute restricts the Cookie to be sent to the server only in HTTPS mode. If the current protocol is HTTP, the browser ignores the Secure attribute sent by the server.

The HttpOnly property specifies that the Cookie cannot be obtained by JavaScript scripts, preventing attacks by malicious scripts.

Cookie and cross domain, security

Cookies are not sent by default when a cross-domain AJAX request is sent. To Allow cookies in cross-domain requests, you need to set the withCredentials request header when initiating the request, and configure the CORS header (allow-cross-with-credentials: true) in the request response.

In a special case, if the withCredentials in cross-domain AJAX requests are configured, even if the response is intercepted by the browser without the CORS headers configured, set-cookies in the response will take effect and cookies can be successfully created. Interested students can see the experience of partners, detailed rules can see the specification.

However, when a cross-domain request is made by the SRC attribute of the IMG tag or script tag, the request carries a Cookie. Form submission cross-domain requests also carry cookies. CSRF attacks are implemented in these ways. You can configure the SameSite attribute of cookies to defend against CSRF attacks. To avoid losses caused by XSS attacks, sensitive cookies should be set to secure and httpOnly attributes.

Two front-end security-related articles are recommended:

  • Front-end Security Series 1: How do I Prevent XSS attacks?

  • Front-end Security Series ii: How to Prevent CSRF Attacks?

Finally, comb through the conditions under which the request carries a Cookie

  • The Cookie is carried only if the domain and path attributes match the requested domain name path
  • If the Secure attribute is present, the request protocol must be HTTPS
  • Cross-domain AJAX requests do not carry cookies, and the withCredentials request headers and CORS response headers need to be configured if they do
  • If the request is cross-site, also determine whether the SameSite attribute meets the send criteria

reference

Cookie and SameSite properties for browser series, by Hu Yu

HTTP cookies, by MDN

Cookie, by Ruan Yifeng