I. Introduction to Cookies
Cookie is a small piece of text information stored locally by the server in the client, the size of each cookie is generally about 4KB, it is like an identity card sent to the client by the server, with this identity card, as long as the client carries this identity card, the server can identify our identity.
Ii. Basic principles of cookies
When visiting a website, the browser will send a request to the server, and the server will return the cookie in the response header after receiving the request. The browser will automatically store the cookie data to the client. When the client visits the server again, each request will carry the cookie, and the server will identify the cookie content. Identify the user or do some special processing and return a response.
Third, cookie characteristics
- Can only store text
- The size of a single storage device is about 4KB
- Quantitative restrictions
- Read with domain name restriction: it cannot be read across domains and can only be read from the web page of the same domain that the cookie was written to
- Time limit: Each cookie has a time limit, and the default time limit is session level: that is, when the browser is closed, the cookie is destroyed immediately, but we can also manually set the expiration time of the cookie during storage
- Path restriction: When storing cookies, you can specify a path. Only the child path is allowed to read the outer layer of cookies, but the outer layer cannot read the inner layer. Cookies are typically stored in the root directory of your project to avoid this problem
Iv. Cookie browser support
V. Use of cookies
-
Session management
- The most common use of cookies is to record a user’s login status. Typically, the server will issue a signature to mark the validity of the session after the user logs in successfully, so that the user does not need to authenticate and log in to the site multiple times.
- Records the user access status
-
Personalized information
- Cookies are also often used to remember user-related information to facilitate the use of their own site services.
- Cookies are also used to remember user – defined functions. When a user sets a custom feature, it is only saved in the user’s browser. In the next visit, the server will show the user’s Settings according to the user’s local cookie.
-
Record user behavior
- Cookies are used to record the user’s operation rate on web pages
Vi. Categories of cookies
1. Session Cookie
This type of cookie is only valid for the duration of the session, that is, it is deleted by the browser when the browser is closed. The way to set a session cookie is to create it without setting Expires.
2. Persistent Cookie
Persistent cookies, as their name implies, persist for a long time in a user session.
3. Secure cookie
A secure cookie is a cookie form under HTTPS access to ensure that the cookie is always encrypted as it passes from the client to the Server. This greatly reduces the probability that cookie contents are directly exposed to hackers and stolen.
4. HttpOnly Cookie
Httponly cookies are supported by all major browsers (Chrome, Safari, Firefox 1.0+, Opera 8.0+, IE5+). On browsers that support HttpOnly, cookies set to HttpOnly can only be passed on HTTP (HTTPS) requests. That is, httpOnly cookies are not valid for client-side scripting language (javascript), thus preventing JS from stealing cookies in cross-site attacks. When you set a cookie with the same name using javascript, only the original HttpOnly value is sent to the server.
5. 3rd-party cookie
The first-party cookie is the cookie planted under the domain name or subdomain name in the browser address bar. Third-party cookies are planted under a domain name different from the browser’s address bar. Such cookies often appear in situations such as advertising services, where advertisers can gather information about a user’s habits and visit history.
6. Zombie Cookie
Zombie cookies are exactly what their name suggests — they come back to life when you think they’re gone.
7. Cookie attribute
- Name Required, specifies the Name of the cookie.
- Value Required, specifies the Value of the cookie.
- Expire/ max-age Optional, specifies the validity period of cookies (default is temporary session, expires when the browser closes).
Expires is a specific expiration date after which the browser will no longer keep the cookie. It is the value of the UTC format, you can use the Date. The prototype. ToUTCString () to convert the format. The max-age attribute specifies the number of seconds the cookie will exist from now on. After this time, the browser no longer keeps the cookie. If both expires and max-age are specified, the max-age value takes precedence. If no expires or max-age attribute is specified, the cookie is a Session cookie, meaning it exists only for this Session and the browser will not keep the cookie once the user closes the browser window.
- Path Specifies the server Path of the cookie. This parameter is optional.
- Domain Specifies the Domain name of the cookie.
Domain specifies the website to which the cookie belongs. For example, baidu.com, the cookie belongs to Baidu.com. Path specifies the path to which the cookie belongs.
- Secure Specifies whether cookies are transmitted over a Secure HTTPS connection.
This field should tell the browser to encrypt the Cookie securely during the HTTPS channel, so that hackers cannot obtain the Cookie even if they are listening.
- Httponly Specifies whether it can only be used for transport
This field tells the browser that it is invisible to the browser’s scripts only when used over HTTP, so cross-site scripting attacks cannot be stolen. Both Google and Facebook use HttpOnly cookies.
- SameSite optional
Samesite-cookies are a mechanism for defining how cookies are sent across domains, The main purpose is to try to prevent CSRF (Cross-site Request Forgery) and XSSI (Cross Site Script Inclusion (XSSI) attacks. Possible values for the sameSite property: When setting the sameSite property for the cookie, you need to define a value for it (if no value is set, it defaults to Strict). The value can be Lax or Strict Strict: When the sameSite property value is strict, sending cookies of all third-party links is prohibited, For example, if there is a cookie (domain = a.com, sameSite = strict), this cookie will not be taken when other websites request a.com: When the sameSite property value is lax, cross-domain cookies are blocked only when they are sent using dangerous HTTP methods, such as POST. For example, if there is a cookie (domain = a.com, sameSite = lax), other websites will not carry this cookie when they request a.com through POST
Cookie setting
Through the above we understand the related knowledge of cookie, next we can set the cookie first must be clear: cookie can be set by the server, also can be set by the client
The cookie is set on the server
The server set the cookie mainly by setting the response header set-cookie to set the cookie. If multiple cookies need to be set, several more set-cookies need to be written.
Nodejs:
res.setHeader('Set-Cookie'['clientlanguage=zh_CN'.'Path=/']);
res.writeHead(200The [['Set-Cookie'.'clientlanguage=zh_CN'],
['Set-Cookie'.'Path=/']
>]); //200 is a three-digit HTTP status code. This parameter is mandatory
Copy the code
The client sets the cookie
Create a cookie
The front end through document.cookie set cookie, set multiple cookies need to write multiple document.cookie = ‘… ‘, you can replace the cookie if you need to modify it and create a cookie with the same name
Create multiple cookies and set path and domain and max-age properties
document.cookie = 'name1=value1; path=/; domain=localhost; max-age=30';
document.cookie = 'name2=value2; path=/; domain=localhost; max-age=30';
document.cookie = 'name3=value3; path=/; domain=localhost; max-age=30';
Copy the code
View cookie information through the Browser console (Chrome)
To get a cookie
The front end can be directly throughdocumentCookies for cookies/ / print the cookie
console.log(document.cookie); // name1=value1; name2=value2; name3=value3
Copy the code
Delete the cookie
There is no direct API in the front end to directly delete cookies. You can set the max-age attribute of cookies0To achieve the deletion of cookies/ / delete the cookie
document.cookie = 'name3=value3; max-age=0; '
Copy the code
Nine, extension,
-
What are the ways to view cookies?
-
What’s the difference between a cookie and a session?
-
Use the code package to simply write a login function, click the login account password to save it in the cookie and set the validity period for 1 minute, jump to the Index page and fill in the account on the page. Index page also has a cookie deletion function, after deleting, manually refresh the page to jump back to the landing page (not deleted by default, one minute after refreshing the page will jump back to the landing page).