• Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

Front-end storage technology

  • Open theChromeThe browser,F12Open the console and clickApplicationItem, sidebarStorageUnder the column of6All of themWeb sideStorage mode
    • LocalStorage
    • SessionStorage
    • Cookies
    • IndexedDB
    • Web SQL
    • Trust Tokens

      The first three storage methods are commonly used, and cookies are the focus here

Cookies

  • Definition:

    • HTTP cookies, commonly called cookies, are used by clients to store session information. This standard requires the server to send a set-cookie HTTP header containing session information as part of the response to any HTTP request.
    • A Cookie is stored in the client browser as part of an Http request. When the browser requests a page, it is automatically sent in the form of an Http request header.

    On the first request, the server stores the cookie in the set-cookie field of the response header and sends it to the client. The client stores the cookie data in the browser memory. On the next request, the browser will automatically store the Cookie data in the Cookie field in the request header and bring it back to the server.

  • Description of configuration options:

    1. The Name & Value

      • Name indicates the Name of the Cookie, and the server obtains the value of a Cookie through the Name attribute.
      • Value indicates the Cookie Value. In most cases, the server will use this Value as a Key to query the saved data in the cache.
    2. SameSite: Strict, Lax, None

      The SameSite property prevents third-party cookies from being sent along with cross-domain requests, preventing cross-site request forgery attacks (CSRF) and reducing security risks.

      • The SameSite property of the Cookie
      • Strict: the strictest, completely forbids third-party cookies, cookies will not be sent under any circumstances when cross-site.

        Cross-domain and cross-site: Cross-domain: Sites with the same scheme, hostname, and port are considered to be in the same domain. Any of these three are not identical and are considered cross-domain. Cross-site: a site and its top-level domain name are considered same-site when both are the same as the domain in front of it (regardless of protocol and port). The reverse is considered cross-station. Check the value of sec-fetch -Site in the HTTP request header to determine whether the request is same-site, same-origin, or cross-site.

      • Lax: The rule is slightly relaxed, and third-party cookies are also not sent in most cases, except for Get requests (links, preloading requests, Get forms) that navigate to the target url.
      • None: None Sends cookies whether cross-site or not, but must be set at the same timeSecureAttribute (cookies can only be sent over HTTPS). Otherwise, the client Block rejects the Cookie, and the Cookie cannot be written.

      Cookies are usually used to store user identity information. Malicious websites can try to forge HTTP requests with the correct Cookie. This is a CSRF attack.

      Chrome93 has made Lax the default for SameSite and can’t set it to None by explicitly turning off the SameSite property via Chrome ://flags/ website.

    3. HttpOnly: true/false;

      • Cookies with the HttpOnly attribute set to true will not be able to use JavaScript viaDocument.cookieAttributes,XMLHttpRequestRequest APIsTo defend against cross-site scripting attacks.

        When HttpOnly is true, clients can neither modify nor delete cookies. There is no way to add cookies with HttpOnly attributes on the client side, but to debug HttpOnly attributes on the client side, you can open Application in Chrome and manually check the corresponding HttpOnly attributes for cookies

    4. Secure: true/false;

      • A cookie with a secure property is sent to the server only if the request uses SSL and HTTPS.
    5. Expires/Max-Age

      • ExpiresSet an expired value for Cookie deletionGMT date
      • Max-AgeSet a Cookie to expiresecondsThe number
      • Note:
        1. Setting both Expires and max-age in the Cookie will ignore Expires and take the max-age value

        2. If neither Expires nor Max-age is explicitly set, the Cookie will act as a Session Cookie and will be deleted when the browser is closed

          Session Cookie data is stored in memory. If the expiration time is set, the browser saves the Cookie to the hard disk

        3. The browser determines whether the Cookie expires based on the local time. After the specified time, the browser does not retain the Cookie

          Since the local time may not be exact, there is no guarantee that cookies will expire at the time specified by the server.

    6. Domain

      • Cookie scope: The Cookie scope isDomainIn itself, andDomainAll subdomain names under.

        Cookies can only be viewed in the current domain and child domains. Cookies cannot be read across domains in parent or sibling domains

      • Parameter values:
        • When there is no explicit settingDomainValue,DomainThe default valueThe current domain name.
          • Cookie is front-end set, the current domain name is the front-end website access domain name
          • Cookies are set at the back end, and the current domain name is the interface domain name of the back end
        • The value can be the parent domain name or itself, but cannot be other domain names, including sub-domain names. Otherwise, the cookie does not take effect.

          To share cookies across multiple secondary domains, set the Domain property to a top-level Domain. When setting it as a top-level domain name, remember to use. Beginning, such as.baidu.com

    7. Path: In Domain scope, access is further restricted by Domain name Path.

      • Parameter Value: The default path is the root path/, i.e.,DomainCookies are accessible to all page paths under the domain name scope
    8. SameParty: This specification is currently only available in Chrome

      • SameParty propertiesNeed to beFirst - Party Sets strategyIt is currently a feature feature and is expected to be widely supported by various browsers in the future.

        SameParty and SameSite will enable cross-domain and cross-site access to Cookies

      • Cookie added SameParty property
    9. Priority: Priority fields, value is low, | medium | high, medium for the default values. The specification is currently only available in Chrome

      • Purpose: It aims to reduce the impact of cookie “eviction” (deletion when the cookie capacity limit for each domain is exceeded) on the user experience.
      • Basic scenario:
        • Scenario problem: Long-standing login session cookies are expelled due to their age, forcing users to lose sessions. Cookie “recovery” occurs when the user re-authenticates.
        • Suggested solution: Add a “priority” field for cookies to allow the server to protect important cookies.
      • Function:
        • Prioritizes cookies when they are revalidated.
        • When cookies exceed the cookie capacity of each domain, they are deleted.
        • Cookie-priority allows the server to delete old cookies with lower priority and stay on cookies with higher priority for longer.
  • Cookie:

    • Running environment: Google Chrome 94.0.4606.54 (official version) (64-bit)
      • Experiments SameSite

      • Chrome Platform Status: Cookie

        Cookies default to SameSite=Lax

    • Front-end setting method:
      • HTTP cookies
      • Native examples:
        let date = new Date(); date.setDate(date.getDate()+30); date.toGMTString(); document.cookie="tokens=GFRTDDFG; SameSite=Strict; Secure; Expires="+ date +";" document.cookie="tokens=GFRTDDFG; SameSite=Strict; Secure; max-age=1000;"Copy the code
      • Vue sample (vue – cookies)
        Vue.$cookies.set("use_path_argument","value",null, null, null, null, "Lax");
        // Vue.$cookies.set(keyName, value[, expireTimes[, path[, domain[, secure[, sameSite]]]]])
        Copy the code
    • Back-end setting method: Node example
      • nodejs response.setHeader
      • expressjs res.cookie
      Res. setHeader(" set-cookie ", "id=123456; Path=/; SameSite=None; Const oneDayToSeconds = 24 * 60 * 60; const token = 123456; res.cookie('token', token, { maxAge: OneDayToSeconds, // The number of seconds the Cookie will expire. If not set, the Cookie will remain until you close the browser. This is called the 'Session Cookie' httpOnly: false, // You can't access these tokens in the client's javascript sameSite: '', // set sameSite - should be one of `None`, `Strict` or `Lax`. // signed: true, // use the secret passed into `express.cookieParser('secret')` to sign the value. secure: process.env.NODE_ENV === 'production'? true: false // Forces to use https in production })Copy the code