What is a Cookie?

Cookie, the name comes from a Fortune Cookie that contains a small piece of paper with a pithy sentence written on it.

In the browser, a Cookie is the server’s way of asking the browser to carry information, like a piece of paper in a Cookie, which the browser stores and sends back to the server in subsequent HTTP requests.

Cookies are used

It is mainly used in 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.)

Because HTTP is stateless, cookies were created to help the Web maintain state. Before HTML5 localStorage and sessionStorage appeared, it was once used for client storage as the only storage means at that time.

With the improvement of the browser storage mechanism, in order to reduce unnecessary performance overhead () for every request browser cookies to carry data, some needs the client and server data of scene gradually replaced by other storage way, remember the theme of user information, for example, cookies application scenario for the slowly return to the beginner’s mind.

At present, cookies are mainly used for session status management. Take user login and logout as an example. The Cookie life cycle is as follows:

The front end passes the user information to the back end through the user login API, and the back end checks whether it matches the database information.

After the match, the login API returns the header set-cookie. The cookie value that records the user’s status is userToken:

Browser according toset-cookieThe rules are parsed and stored in the browser

The browser will automatically add the userToken to the request header cookie of the API that meets the criteria (domain name, path)

If logged out, return the headerset-cookieWill ask the browser to delete the userToken, the browser’s cookie repository will delete the userToken field, subsequent API request headercookieIt doesn’t send it

How to set cookies

The server and browser have different ways of setting cookies.

Quick table

platform The operation sample instructions
The service side set-cookie: <cookie-name>=<cookie-value> The server controls cookies by setting set-cookie
The browser

document.cookie
document.cookie = ; Getting and setting cookies associated with the current document is inflexible.

Learn more about
The browser

Cookie Store API
cookieStore.set(“name”, “scar”) The new feature, which supports HTTPS only, is still in the experimental phase.

Learn more about

Detailed instructions

Server: set-cookie

Node.js is used as an example on the server. Different languages have different usage, but the Cookie setting logic is the same

const http = require("http");
http
  .createServer((req, res) = > {
    if (req.url === "/read") {
      / / read cookies
      res.end(`Read Cookie: ${req.headers.cookie || ""}`);
    } else if (req.url === "/write") {
      / / set the Cookie
      res.setHeader("Set-Cookie"[`name=scar; `.// Set-cookie is case-insensitive. You can write path=/ or path=/
        `language=javascript; Path=/; HttpOnly; Expires=The ${new Date(
          Date.now() + 1000
        ).toUTCString()}; `,]); res.end("Write Success");
    } else if (req.url === "/delete") {
      / / delete the cookie
      res.setHeader("Set-Cookie"[// Set the expiration time to the past time
        `name=; expires=The ${new Date(1).toUTCString()}`.// The validity period max-age is set to 0 or -1, which is an invalid second, so that the cookie dies instantly
        // Some browsers do not support the max-age attribute, so use this method for compatibility reasons
        "language=javascript; max-age=0",]); res.end("Delete Success");
    } else {
      res.end("Not Found");
    }
  })
  .listen(3000);
Copy the code

Client: document.cookie

The client reads and writes the cookie of the current interface through the browser method document.cookie.

/ / edit ookie
document.cookie = "name=scar";
document.cookie = "language=javascript";
/ / read cookies
console.log(document.cookie);
//name=scar; language=javascript

/ / delete the Cookie
document.cookie = "name=scar; expires=Thu, 01 Jan 1970 00:00:01 GMT";
Copy the code

Client: Cookie Store API

The Cookie Store API is currently in the experimental stage. Firefox and Safari do not support it yet, so it is not recommended to use it in production environments. I believe we will use it in the future to make it easier to operate cookies

/ / read cookies
await cookieStore.get("enName");
await cookieStore.getAll();

/ / set the Cookie
const day = 24 * 60 * 60 * 1000;
cookieStore
  .set({
    name: "enName".value: "scar".expires: Date.now() + day,
    domain: "Scar. SiteI",
  })
  .then(
    function () {
      console.log("It worked!");
    },
    function (reason) {
      console.error("It failed: ", reason); });/ / delete the Cookie
await cookieStore.delete("session_id");

// Listen for Cookie changes
cookieStore.addEventListener("change".(event) = > {
  for (const cookie of event.changed) {
    if (cookie.name === "name") sessionCookieChanged(cookie.value);
  }
  for (const cookie of event.deleted) {
    if (cookie.name === "enName") sessionCookieChanged(null); }});Copy the code

In addition to more convenient usage, it has the following features:

Asynchronous operations

It can access cookies asynchronously without blocking the main process, and document. Cookie is a synchronous operation

Error throwing mechanism

The Cookie Store API has an explicit mechanism to report Cookie storage errors, and document. Cookie will not be alerted if the setting fails, so you need to query the Cookie method to ensure that the setting succeeds.

Service workers support

Service Workers are not supported because of the synchronous design of Document. cookie. The asynchronous nature of the Cookie Store API is more appropriate, so Service Workers support access to cookies through it.

The Set – cookies explanation

From the syntax, set-cookie consists of prefix, key-value pair, and attribute.

Set-Cookie: <cookie-name>=<cookie-value>
Set-Cookie: <cookie-name>=<cookie-value>; Expires=<date> // Specify multiple attributes Domain, Secure, and HttpOnlySet-Cookie: <cookie-name>=<cookie-value>; Domain=<domain-value>; Secure; HttpOnly // The cookie prefix, which can be __Secure- or __Host-Set-Cookie: <cookie-prefix><cookie-name>=<cookie-value>
Copy the code
  • Prefix [not required]

    • Example:Set-cookie: __Secure-lol=foo; Domain=example.xxx_Sercure- is the prefix
    • The Cookie prefix must be used together with attributes to ensure Cookie security
  • Key-value pairs (name = value)

    • Example:Set-cookie: __Secure-lol=foo.
    • Cookies carry information
  • Attributes [not required]

    • Example:Domain=somecompany.co.uk; Path=/; Expires=Wed, 30 Aug 2019 00:00:00 GMT
    • Cookie Settings, tell the client how to use Cookie information, you can set the Cookie effective time, domain name and other information.

Cookie prefix

A Cookie prefix is a way to carry information in the Cookie name. It must be accompanied by certain attributes, otherwise the Cookie cannot be set successfully.

The name of the instructions
__Secure- You must also set the Secure property
__Host- The Path=/ and Secure attributes must be set at the same time, and the Domain attribute cannot be set.

Prevents cookies from being applied to insecure domains

Example:

// Those that support Cookie prefixes reject the following Settings because Secure is not set at the same time
document.cookie = "__Secure-invalid-without-secure=1";
// The setup will succeed!
document.cookie = "__Secure-valid-with-secure=1; Secure";
Copy the code
// When the response comes from a secure domain (HTTPS), both can be accepted by the clientSet-Cookie: __Secure-ID=123; Secure; Domain=example.com
Set-Cookie: __Host-ID=123; Secure; Path=/ // The Secure attribute is missing and will be rejectedSet-Cookie: __secure-id =1 // Will be rejected if Path=/ is missingSet-Cookie: __Host-id=1; Secure
Copy the code

To be honest, IT’s a prefix I’ve never seen before. I don’t know much about it.

Internet Explorer does not support, other major browsers support basic. Set-Cookie: __host-id =1; Set-Cookie: __host-id =1; When Secure sets the __Host- prefix, Even if Path=/ is missing, FireFox can set it successfully and Chrome will reject it.

But why?SecureProperty plus one__Secure-The prefix?

The Secure attribute can be maliciously removed, while the Cookie name will not be recognized by the server if the prefix is removed, so it is more Secure.

Cookie key-value pairs

<cookie-name>=<cookie-value>
Copy the code

The part that actually carries information, for example:

id=38afes7a8
Copy the code


can be any US-ASCII character except control characters (CTLs), Spaces, or tabs. It cannot contain the following delimiter characters: () < > @,; : “/ []? = {}.


Optional. If there is a value, it must be enclosed in double quotation marks. Supports any US-ASCII characters except control characters (CTLs), Spaces (whitespace), double quotes, commas (comma), semicolon (backslash).

Cookie attribute

The Cookie attribute can be understood as the configuration item of the Cookie, which tells the browser some additional information about the Cookie, such as when does the Cookie expire

Quick table

Cookie attribute instructions type The default value The sample
Domain Effect of the domain name String The host part of the current access address scar.site
Path Effective path String / /docs
Expires Expiration time Date Browser session closing time Thu, 22 Jul 2021 00:53:13 GMT
Max-Age Validity period, in seconds Number 1000
Secure Only HTTPS available There is no value, set as soon as it appears
HttpOnly Cookies with the HttpOnly attribute set cannot be accessed using JavaScript There is no value, set as soon as it appears
SameSite Allows the server to set cookies not to be sent with cross-site requests string Value possibility is:

Lax

Strict

None
SameParty Allows specific conditions to share cookies across domains There is no value, set as soon as it appears
Priority Priority, supported only by Chrome Medium Value possibility is:

Low

Medium

High

Detailed instructions

Domain

Domain specifies which host addresses can receive cookies. Take a look at the following Settings:

Set-Cookie: __Secure-ID=123; Secure; Domain=example.com
Copy the code

Cookies will be sent as long as the destination address of the request matches the Domain rule, so cookies will be sent even if scar. Site makes a request to example.com. Domain is the Domain that initiates the request. Domain is the Domain that receives the request.

If this parameter is not set, the default value is Origin and the Cookie does not contain a subdomain name. If Domain is specified, the Cookie usually contains a subdomain name. For example, if Domain=mozilla.org is set, cookies are also contained in the subdomain name, such as developer.mozilla.org.

Most browsers currently follow RFC 6265 and do not need to add a leading dot when setting a Domain. If the browser does not comply with this specification, add a preceding dot, for example, Domain=.mozilla.org

Path

The Path identifier specifies which paths under the host can accept cookies (the URL Path must exist in the request URL). Child paths are also matched with the character %x2F (“/”) as the path separator.

For example, if Path=/docs is set, the following addresses will match:

  • /docs
  • /docs/Web/
  • /docs/Web/HTTP

Expires

To set the expiration time, you can pass a value in the HTTP-date format, for example, Expires =Mon, 14 Mar 2022 15:39:34 GMT.

If Expires is not set, it defaults to the session closure time.

A session is a browser concept, typically a browser Tab window.

If the browser provides session recovery, the Cookie is also restored when the session is resumed, as if the session had never been closed.

Max-Age

The number of seconds that need to pass before the Cookie expires. A number of seconds of 0 or -1 will expire the cookie directly. Some older browsers (IE 6, IE 7, and IE 8) do not support this property.

If both Expires and max-age exist, max-age takes precedence.

HttpOnly

Cookies with HttpOnly attributes cannot be accessed using JavaScript via the Document.cookie attribute, XMLHttpRequest and Request APIs, and the Cookie Store APIs.

Secure

Cookies marked Secure are sent to the server only through requests encrypted by THE HTTPS protocol, thus preventing man-in-the-middle attacks.

But even if Secure flags are set, sensitive information should not be transmitted through cookies. Because cookies are inherently insecure, Secure flags do not provide a real guarantee of security, for example: someone with access to a client’s hard drive can read it.

SameSite

The server prevents cross-site request forgery attacks by requiring that a Cookie not be sent during a cross-site request.

SameSite can have the following three values:

  • None: The browser continues to send Cookies on same-site or cross-site requests, case insensitive.

  • Strict: The browser will only send a Cookie if the visited site is in the same domain as the Cookie.

  • Lax: The default setting of the new browser is Lax. Similar to Strict, but specific conditions can also send cross-domain requests:

    • The URL must change

    • HTTP requests must be secure, such as GET, HEAD, and OPTIONS, which do not alter data.

    For example, when the user jumps from a.com to b.com, the URL changes and the request mode is GET, so the Cookie with Lax set will be sent, and there will be image loading, iframe call, and so on.

Differences between SameSite and Domain

As mentioned above, the Domain can specify the Domain name that the Cookie takes effect. What is the difference between Domain and Domain?

DomainProperty limits the domain by which cookies are received, whileSameSiteProperty limits the domain to which cookies are sent

Here’s an example:

Set-Cookie: Foo=bar; Path=/; Secure; Domain=scar.site;
Copy the code

Cookies can be sent to either scar. Site or foo.example.com if a request is sent to scar. Site or its subdomain.

Set-Cookie: name=scar; Path=/; Secure; Domain=scar.site; SameSite=strict;Copy the code

If SameSite=strict, the request can only be sent from scar. Site to the Cookie.

SameParty

It’s still in the experimental stage

With first-party Sets to implement cross-domain sharing properties, you can visit the SameParty property added to Cookie for details.

Priority

Currently only Chrome implements this proposal

Because there is a limit on the number of cookies, when the number of cookies exceeds a certain number, the browser will clear the earliest expired cookies.

If Priority is set, Chrome clears low-priority cookies and reserves at least one Cookie of each Priority. There are three possible values:

  • “Low” : indicates the Low priority

  • Medium: default value, Medium priority

  • “High” : indicates the High priority

Q&A

Some questions and new features about cookies are recorded in Q&A form. More miscellaneous, more scattered, it can be said that no knowledge point is feelings, belong to the kind of you know it may not have much use but want to understand it.

1. Cookie restrictions

Size limit

Most browsers support cookies of up to 4KB, which is the Value of a single record for cookies.

Quantitative restrictions

Cookies are limited in number, and only a certain number are allowed to be stored on each site. When these are exceeded, the earliest expired cookies are deleted.

The number of different browsers may vary, based on Webkit kernel is 180, based on gECko kernel is 150, interested in visiting Jiang Tao learning programming – written Cookie experiment to try their own browser Cookie number limit

In fact, there are not only Expires and Max-age factors that affect Cookie deletion, but also Priority and Secure. For those who are interested in removing policies, see Cookie knowledge two

2. What are the insecure events related to cookies?

CSRF attacks

CSRF: Cross-site request attack, simply put, is the attacker through some technical means to trick the user’s browser to visit a previously authenticated website and perform some operations (such as sending emails, sending messages, or even property operations such as transferring money or buying goods).

For example, a bank would use the following URL to run a transfer operation:

http://www.examplebank.com/withdraw?account=AccoutName&amount=1000&for=PayeeName
Copy the code

Then, a malicious attacker could place code like this on another site:

<img src="<http://www.examplebank.com/withdraw?account=scar&amount=1000&for=Badman>">
Copy the code

If a user with the account name Alice visits a malicious site, but she has recently visited the bank and her login information has not expired, the backend assumes that the user is doing the normal operation and deducts the money, she will lose 1000 funds. Setting sameSite prevents cross-domain Cookie sending and resists CSRF.

XSS attacks

Cross-site scripting is a web application security vulnerability attack known simply as CSS, but this can be confused with the abbreviation for Cascading Style Sheets CSS. Therefore, cross-site scripting attacks are abbreviated to XSS.

XSS attack usually refers to the use of the vulnerabilities left in the development of the web page, through a clever way to inject malicious command code into the web page, the user load and execute the malicious web program made by the attacker. After a successful attack, the attacker may obtain cookies to implement the attack.

3. Floc instead of third-party cookies?

From: Would Google FLoC be a better alternative to third-party cookies? – the minority

FLoC is a new ad-tracking technology called Federated Learning of Cohorts. FLoC works by monitoring your browsing history, assigning an ID to the aggregated behavior of visitors, and then grouping browsers with similar browsing behavior. The data from these groups, called peer groups, is then used to show people more targeted ads.

FLoC is more private than cookies by design, but it is still an AD tracking technology first, and a relatively privacy-protecting AD tracking technology second.

FLoC is dominated by Google, so the tripartite group is concerned that when all browsers start blocking third-party cookies by default and advertisers switch to FLoC, Google will dominate the ad-tracking market.

4. How to determine the priority of cookies with the same name?

Cookie: a=2; a=1
Copy the code

First, let’s look at the order in which cookies are sent. Proposal RFC 6265 states:

  • The longer Path attribute should come first

  • If the paths are the same, the creation time is earlier

I didn’t go into the specifics of browser behavior, but the proposal is just an advocacy, so each client doesn’t necessarily send cookies in the order it implements them.

In addition to the sending order, it is also necessary to consider that different server frameworks may have different receiving logic. Therefore, the author recommends to avoid Cookie with the same name as possible to reduce the uncertainty caused by inconsistent end performance.

5. How to debug cookies quickly

F12 Open the console to quickly see all cookies in the local domain

Analyze Cookie properties to locate problems.

For example, if a Cookie causes a business problem, if it is set to HttpOnly, then it means that the client cannot manipulate the Cookie, and can quickly locate the problem at the API level.

conclusion

Originally, I was writing: Cookie, Session, Token, but I wrote that the discovery of Cookie was too long, and the focus of the article was not on these parts, so I picked them out. If you are interested in Cookie, Session and Token, please keep following me. I will send you a message soon

As a front-end staff, I am not familiar with cookies because I seldom use them, but there is no difficulty after understanding them. I believe that you can thoroughly understand cookies after reading this article. If there’s anything else in the article that you want to know about cookies that I haven’t written, you can comment and I will respond.

data

  • Cookies – mozilla
  • Set-Cookies – mozilla
  • How does Cookie prefix make cookies more secure? – Aliyun Community
  • What is a Session Cookie?
  • View, edit, and delete cookies
  • Correct way to delete cookies server-side
  • Feature: Cookie Store API
  • Interview: Thoroughly understand cookies and Cookie security
  • Is Google FLoC a better alternative to third-party cookies? – the minority
  • What is FLoC? And why you need to disable it in Chrome · Ruby China
  • Share the results of an experiment done on cookies – Ataola – Blog garden
  • What are the security differences between cookies with Domain vs SameSite strict? – Stack Overflow
  • What is difference between SameSite=”Lax” and SameSite=”Strict”? – Stack Overflow
  • Cookie knowledge two
  • How to handle multiple cookies with the same name? – Stack Overflow