A Cookie.

Cookie concept

Concept: Essentially a small text file stored in a browser (or possibly local), with user state stored internally as key-value pairs.

Cause of Cookie

Reason :HTTP is a stateless protocol, can not save the context of the request response information, but sometimes need to save the previous state, to solve this problem introduced cookies. Cookie solves the problem of client – server session state.

Cookie header field

There are two main ones

  • Set-Cookie
  • Cookie

Set-Cookie

Function: Sets the Cookie information to be sent to the client in the header of the response packet

Such as:

Set-Cookie: name=xxx; HttpOnly
Copy the code

Cookie

Function: Cookie information passed from a client to a server

Such as:

Cookie: name=xxx
Copy the code

The interaction process

The Cookie interaction between the client and server is as follows:

  1. The client requests the server
  2. The server generates Cookie information and adds it to the header of the response packet using set-cookie
  3. The client saves the Cookie after retrieving it
  4. The next request is sent to the server by writing the information into the Cookie field in the request header

Cookie life cycle

  • By defaultCookieThey are transient, meaning their storage lasts only for the duration of the browser session and expires when the user closes the browser
  • To use theexpiresandmax-ageTo set theCookieExpiration time of

expires=DATE

Effect: To set the Cookie expiration time, a specific time.

Default: Defaults to the current time of the set Expires.

Case study:

For example, in back-end code:

ctx.cookies.set("token", '112233', {expires: new Date(+new Date() + 1000 * 60 * 60 * 24 * 7),
})
Copy the code

The header field of the response body of the interface request has:

Set-Cookie: token=112233; Expires =Wed Aug 12 2020 21:55:03 GMT Copies the codeCopy the code

max-age=TIME

Function: Sets the Cookie expiration time, in seconds, from the time the client receives the packet.

Default value: -1.

Use expires the same way:

For example, in back-end code:

ctx.cookies.set("token", '112233', {
	max-age: 36000,
})
Copy the code

The header field of the response body of the interface request has:

Set-Cookie: token=112233; max-age=36000	
Copy the code

In addition, attribute values are divided into the following three types for easy memorization:

  • 0: Delete this immediatelyCookie
  • Positive: the browser persists itCookieIn the
  • Negative: sessionCookie

In view of the above 👆 three situations, the interview may encounter questions:

Q1: What happens if cookie max-age is set to 0?

A: If max-age is 0, the cookie is deleted. The cookie mechanism does not provide a method to delete the cookie. Therefore, the cookie can be immediately invalidated to achieve the effect of deleting the cookie. Invalid cookies are deleted from the Cookie file or memory by the browser.

Q2: What happens when you close the browser if you set the max-age property of the cookie to a positive number?

A: If the max-age attribute is positive, it indicates that the cookie is automatically invalid after the max-age seconds. The browser will persist cookies with a positive max-age value, that is, write them to the corresponding cookie file. The cookie remains valid when the customer logs in to the site, regardless of whether the browser or computer is closed, as long as it is before max-age seconds.

Q3: What happens if the max-age property of the cookie is set to be negative?

A: If max-age is negative, it indicates that the cookie is valid only in the browser window and its child Windows. The cookie becomes invalid after the window is closed. A Cookie whose max-age is negative is a temporary Cookie and will not be persisted or written into the Cookie file. Cookie information is stored in browser memory, so the cookie disappears when the browser is closed. The default max-age value for cookies is -1.

scope

For the scope of Cookie, it means to bind the domain name and path to Cookie. If the two attributes of domain name or path do not match before sending a request, the Cookie will not be carried. Generally speaking, it is under what circumstances to carry cookies

What are the header fields of Cookie scope?

  • Domain = domain name
  • path=PATH

Domain = domain name

Function: Specifies the host name to which the Cookie can be delivered.

Such as:

Set-Cookie: domain=.example.com
Copy the code

path=PATH

Function: To specify a URL path, the Cookie head is added only to the header of the request packet with the specified URL path.

The default value is: /, which means that all URL paths carry cookies.

For example:

Set-Cookie: name=xxx; path=/docs
Copy the code

Only resources under /docs will have cookies, and another directory named /test will not.

security

The security of Cookie is also a common question, which involves the main attributes of the header field:

  • Secure
  • HttpOnly
  • SameSite

Secure

Effect: The secure property is set, which indicates that cookies are transmitted only over HTTPS.

Such as:

Set-Cookie: name=xxx; secure
Copy the code

HttpOnly

Function: Cookies with HttpOnly can only be transmitted through HTTP protocol, cannot be accessed through JS script files (document. Cookie).

Such as:

Set-Cookie: name=xxx; HttpOnly
Copy the code

Cookies with the HttpOnly flag set can only be used during HTTP requests and cannot be read with JS scripts. Because many XSS attacks are by stealing cookies, so the HttpOnly attribute can also protect our Cookie security, is a kind of important means to prevent XSS attacks.

SameSite

Function: Used to restrict third-party cookies, generally used to prevent CSRF attacks.

Default: None before Chrome80, Lax after Chrome80.

Such as:

Set-Cookie: name=xxx; SameSite=Lax
Copy the code

SameSite can be set to three values, Strict, Lax, and None.

  1. inStrictIn this mode, the browser does not allow third-party requests to carry cookies. Such as requestxiaohei.comThe website can only be accessedxiaohei.comCookies can only be carried by requests in domain names, not requests on other sites.
  2. inLaxMode, a little bit looser, but only inThe get method submits the formConditions orThe A tag sends a GET requestCan carry cookies in other cases.
  3. In None mode, cookies are sent in all contexts, that is, across domains.
What should I pay attention to when using SameSite?
  • For default values,Chrome80It’s always beenNoneIn theChrome80For after Lax.
  • HTTPInterface not supportedSameSite=None, must cooperateSecureProperty that represents only theHTTPSSend only under the protocolCookie;
  • Need to beUACheck, some browsers cannot addSameSite=None.IOS12theSafariAnd the oldChromeThe browser will putSameSite=NoneAs aSame=StrictSo we need to useUser-AgentObtaining browser information is not delivered to some browsersCookie

The actual use of cookies

There are many practical uses of cookies, mainly including:

  • 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.)

disadvantages

  • Capacity defects. Cookies have a maximum size of 4KB and can only be used to store small amounts of information.
  • Performance defects. The Cookie follows the domain name, and the request carries the complete Cookie regardless of whether an address below the domain name needs the Cookie or not, making the request carry unnecessary parameters. But this can be resolved by specifying the scope of Domain and Path
  • Security defects. Because cookies are passed in plain text between browsers and servers, they can easily be intercepted by illegal users. HttpOnly false can be obtained from the JS script.

The second Session.

Concept of the Session

Session is another mechanism for recording the client’s state, except that cookies are stored in the client browser, while sessions are stored on the server. When the client browser accesses the server, the server records the client information in some form on the server. So that’s Session. The client browser only needs to look up the client’s status from the Session when revisiting.

Cause of Session

The reason is similar to Cookie.

The interaction process

If the Cookie mechanism determines the identity of a customer by checking the “pass” on the customer, the Session mechanism determines the identity of the customer by checking the “customer list” on the server.

  • The server assigns a different identity to each client
  • And then every time the client sends a request to the server, it carries this “identity tag.”
  • For browser clients, everyone defaultscookieThe way to save this “id”.

The difference between Session and Cookie

  1. cookieThe data is stored on the client’s browser,sessionData is stored on the server;
  2. cookieIt’s not very secure. Someone can analyze it and store it locallyCOOKIEAnd carry onCOOKIEDeception should be used for safety reasonssession;
  3. sessionIt will be stored on the server for a certain amount of time. When the number of visits increases, it takes a lot of performance out of your server. Should be used in terms of reducing server performanceCOOKIE;
  4. The limit of a single cookie on the client is 4K, that is, a site cannot store more than 4K cookies on the client.
  5. server-sidesessionImplementation on the client sidecookieIf there are dependencies, the server executes themsessionMechanics are generated whensessionThe id value of theta, this oneidThe value is sent to the client and stored incookieIn the.

3. LocalStorage and sessionStorage and indexDB

localStroage

And the similarities and differences between the Cookie

Similar to cookies, localStorage is specific to a domain name. That is, the same segment of localStorage will be stored under the same domain name.

However, there are quite a few differences between cookies:

  1. Capacity. The maximum capacity of localStorage is5MCompared withCookie4K has been greatly increased. Of course this 5M is for a domain name, so it is persistent for a domain name.
  2. Only clients exist and do not communicate with the server by default. This is a good way to avoid performance and security issues with cookies.
  3. Interface encapsulation. throughlocalStorageExposed globally and through itsetItem 和 getItemAnd other methods for operation, very convenient.

Application scenarios

Using localStorage’s large capacity and persistent features, you can use localStorage to store some stable resources, such as the official website logo, store Base64 format image resources, so use localStorage

sessionStorage

The characteristics of

SessionStorage is the same as localStorage in the following aspects:

  • Capacity. The maximum capacity is 5M.
  • Only clients exist and do not communicate with the server by default.
  • Interface encapsulation. In addition tosessionStorageThe name has changed, storage mode, operation mode andlocalStorageThe same.

However, there is an essential difference between sessionStorage and localStorage, that is, sessionStorage is only session level storage, not persistent storage. The session ends, that is, the page closes, and this part of the sessionStorage ceases to exist.

Application scenarios

  1. You can use it to maintain form information, store form information in it, and ensure that the previous form information will not be lost even if the page is refreshed.
  2. You can use it to store the browsing history. If these records are not needed after closing the page, usesessionStorageIt would be perfect. In fact, weibo has taken such a way of storage.

IndexedDB

IndexedDB is a non-relational database that runs in the browser. It is essentially a database, and is by no means on the order of 5M for WebStorage, which is theoretically unlimited.

conclusion

  1. cookieIt’s not good for storage and has a lot of bugs.
  2. Web StorageincludinglocalStorageandsessionStorage, does not participate in communication with the server by default.
  3. IndexedDBProvides an interface for storing large data for non-relational databases running on browsers.