cookie

What is a cookie?

Because HTTP is a stateless protocol, the server cannot know the identity of the client from the network connection alone. In this case, the server needs to issue a cookie to the client to confirm the user’s identity.

To put it simply, cookie is a mechanism for the client to save user information, which is used to record some user information.

Principle: The Web server adds a set-cookie response header field to the HTTP response header to send Cookie information to the browser, and the browser adds a Cookie request header field to the HTTP request message to send the Cookie back to the Web server.

The composition of the cookie

The server sends cookies to the client through HTTP response packets. Set the cookies to be sent to the client in set-cookie format as follows:

Set-Cookie: "name=value; domain=.domain.com; path=/; expires=Sat, 11 Jun 2019 11:29:42 GMT; HttpOnly; secure"
Copy the code

Name =value is mandatory and other options are optional. The main composition of Cookie is as follows:

  • Name: a uniquely identified cookie name. Cookie names are generally case insensitive.

  • Value: string value stored in cookies. It is best to urL-encode the name and value of cookies

  • Domain: The domain for which the cookie is valid. This cookie information is included in all requests sent to the domain. This value may or may not include a subfield (e.baidu.com) (.baidu.com, which is valid for all subfields of baidu.com).

  • Path: indicates the path affected by the cookie. According to this configuration, the browser will send the cookie to the path matching the specified field.

  • Expires: A timestamp that indicates when the cookie should be deleted (that is, when it should stop sending the cookie to the server). If you do not set this timestamp, the browser will delete all cookies when the page closes; But you can also set your own deletion time. This value is in GMT format. Using Expires can be biased if the client-side and server-side times don’t match. And if you set the cookie to a past time, the browser will immediately delete the cookie

  • Max-age: Like expires, it tells the browser how long the cookie will expire (in seconds), rather than a fixed point in time. Normally, max-age takes precedence over Expires.

  • HttpOnly: tells the browser that it is not allowed to change this value through the document.cookie script and that this value is also not visible in document.cookie. But HTTP requests still carry this cookie. Note that although this value is not available in the script, it still exists as a file in the browser installation directory. This setting is usually set on the server side.

  • Secure: indicates the security flag. If this parameter is specified, the message is sent to the server only when SSL links are used. If HTTP links are used, the message is not transmitted.

It is emphasized that cookies are not cross-domain. Many websites use cookies. Different browsers save cookies in different ways, and cookies of each website can only be used by the corresponding website. That is to say, when the browser visits Baidu, it will only bring the Cookie of Baidu, but not the Cookie of other websites, which is the non-transdomain property of Cookie. Cookies are managed by the browser on the client side. The browser can ensure that each website can only operate the cookies of each website, so as to ensure the privacy security of users.

The characteristics of the cookie

Cookies do not provide modification or deletion operations

If you want to modify a Cookie, you only need to create a Cookie with the same name and add it to Response to cover the original Cookie.

If you want to delete a Cookie, you only need to create a Cookie with the same name, set maxAge to 0, and add it to Response to override the original Cookie. Notice it’s 0, not negative. Negative numbers mean something else.

Note: When modifying or deleting cookies, all attributes of the new Cookie except value and maxAge, such as name, path and domain, must be exactly the same as the original Cookie. Otherwise, the browser will not overwrite the cookies as two different cookies, resulting in the modification and deletion failure.

session

What is 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. The client browser only needs to look up the client’s status from the Session when revisiting

The working steps of the session

Because the HTTP protocol is stateless, a Session cannot determine whether it is the same user based on the HTTP connection. The server sends a Cookie to the user’s browser named JESSIONID, whose value is the Session ID value. This id allows the Session to identify the same user based on the Cookie.

To put it simply: a Session can identify different users by relying on cookies. Therefore, a Session is based on cookies

The Cookie is automatically issued to the browser by the server, and we do not need to create it manually. The maxAge value of the Cookie is -1 by default, which means that the Cookie is only used by the current browser and not stored in the hard disk. Moreover, the Cookie is not shared between browser Windows, and the browser will be invalid after closing.

Working procedure: The client is called client and the server is called server

  1. Generate sessionID: Session is a cookie-based scheme, so the first step is to generate a cookie. When the client accesses the server for the first time, the server generates a random number named sessionID and returns it to the client in the form of a cookie. The client processes this cookie in the same way as other cookies. Cookie: sessionID=135165432165

  2. Save sessionID: The server stores the data in the corresponding sessionID, and stores the sessionID in the special memory on the server (such as a hash table called session).

  3. Use session: When the client accesses the server again, it carries the cookie with the sessionID obtained during the first access. The server reads the sessionID in the cookie. Search for data matching the sessionID based on the sessionID to the memory that stores the session. If the search succeeds, the data is returned to the client.

Session validity period

The Session is stored on the server side. For faster access, servers typically store sessions in memory. Each user will have a separate Session. If the Session content is too complex, it can cause memory overflow when a large number of clients access the server. Therefore, the information in the Session should be as minimal as possible.

After a Session is generated, the server updates the last access time of the Session and maintains the Session as long as the user continues to access the Session. Each time a user accesses the server, regardless of whether the user reads or writes a Session, the server considers that the user’s Session is active.

As more and more users access the server, more and more sessions are created. To prevent memory overflow, the server removes sessions that have not been active for a long time from memory. This time is the Session timeout. If the server is not accessed after the timeout period, the Session is automatically invalidated.

The difference between cookies and sessions

  • Cookie data is stored on the client and Session data is stored on the server

  • Cookie security is general, others can analyze cookies stored locally and cheat cookies. On the premise of security first, Session is preferred. Important interaction information, such as permissions, is stored in the Session, and general information records are stored in cookies

  • A single Cookie can store no more than 4K of data. Many browsers limit the number of cookies a site can store to 20, and Session has no limit in principle

  • Sessions are stored on the server for a certain amount of time. Cookies should be used to reduce server performance when the number of accesses increases.

  • A Session relies on the Session ID, and the Session ID is stored in the Cookie. That is, if cookies are disabled by the browser, the Session is invalid (but this can be done in other ways, For example, passing the Session ID in the URL (address rewriting)

localStorage

What is the localStorage?

LocalStorage is an API provided by HTML5, which is essentially a hash, which is a hash that exists in the browser.

The localStorage life cycle is permanent, which means that localStorage information will remain forever unless the user displays it on the browser-provided UI and clears it. The size of stored data is generally 5MB, and it is only stored in the client (i.e. browser), and does not participate in the communication with the server.

LocalStorage Usage

LocalStorage and sessionStorage use the same API:

localStorage.setItem("key"."value"); // Store a value "value" with the name "key"localStorage.getItem("key"); // Get the value named "key"localStorage.removeItem("key"); // Delete the information named key.localStorage.clear(); / / to emptylocalAll information in StorageCopy the code

LocalStorage is a client hash table that can be used to store local data. And it is not released for refreshing, so you can use localStorage to implement persistent storage of variables

The characteristics of localStorage

  • LocalStorage has nothing to do with HTTP, so HTTP requests do not carry a value for localStorage

  • Only pages with the same domain name can read localStorage from each other. The same-origin policy is consistent with cookie

  • Different browsers have different regulations on the maximum storage capacity of each domain name localStorage. If the storage capacity exceeds the maximum, the storage capacity will be rejected. The maximum value is 5M. If the value exceeds 5M, the data will be lost. Chrome is around 10MB

  • Often used to record insensitive information

  • LocalStorage is theoretically permanent unless the user clears the cache

sessionStorage

All properties of sessionStorage are basically the same as localStorage, the only differences are: SessionStorage lasts for the duration of the page session. If the page session ends (close the window or TAB), the sessionStorage disappears. LocalStorage will always exist.

LocalStorage and sessionStorage

  • The localStorage life cycle is permanent and is saved permanently unless cleared, while sessionStorage is only valid for the current session and is cleared after closing the page or browser

For details, see localStorage. The size of data stored in these two storage modes is generally 5MB, and they are stored only in the client (browser) and do not communicate with the server.


C_C