This is the third day of my participation in the November Gwen Challenge. Check out the details: the last Gwen Challenge 2021
Blogger after summarized the experience on a large number of interview, found that the examination site about cookies is the darling of the interviewer, whether in the scenario, after work or on the interview, it is our inevitable a barrier, so, let’s get together to cross the line, have the courage to face it, no difficulty can’t be solved.
A, Cookie,
What is a Cookie
HTTP is stateless protocol, no memory for transaction processing, each client and server session is completed, the server will not save any session information, each request is completely independent, if the server wants to confirm the identity of the current visitor, it must actively maintain a state. This state is used to inform the server whether two requests from the same client before and after, this state is needed by cookies or session to implementation, the cookie is the server sends to the user’s browser and a short block of data stored in the local, it will be the next to the same server to the browser was caught and sent to the server to carry a request.
Whether cookies can cross domains
Cookies are not cross-domain. Each Cookie is bound to a single domain name and cannot be obtained and used under other domain names. Level-1 domain names and level-2 domain names are allowed to be shared through domains. For example, Baidu.com is a level-1 domain name, and asdx.iisp.com is a level-2 domain name.
The main use of cookies
- 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.)
How do I implement cookies across domains
When a browser initiates a cross-domain request, it does not proactively carry cookies. To achieve cross-domain cookie acquisition, you can perform the following Settings.
- The front end sets the withCredentials to true when sending requests.
- The back end sets the value of the access-Control-Allow-Origin field to the domain name that initiates the request.
- The access-Control-allow-credentials header is set to true on the backend.
How are cookies saved locally?
The server can return the response header, set-cookie field, and set the corresponding value.
Various properties of cookies
1. name
Name indicates the name of the cookie. Cookies in a domain name cannot have the same name, because the same name will be overwritten.
2. value
The value property represents the value of the corresponding cookie.
3. domain
Domain attribute represents the domain name bound by cookie. If it is not set, it will be automatically bound to the current page executing the statement. Secondary domain names under the same domain name cannot exchange cookies, such as www.baidu.com and image.baidu.com. However, if it is set to. Taobao.com, cookies can be used by both a.taobao.com and b.taobao.com. It should be noted that cookies cannot be set across domains.
4. path
Path specifies a subdirectory that can share cookies. The default directory is the root directory, so that all subdirectories can share cookies. If a subdirectory is set, its parent directory cannot access cookies, but its subordinate directories can share cookies. Domain and path together identify the scope of the Cookie, that is, the URL to which the Cookie should be sent.
5. Expires/Max-Age
This property is used to set the validity period of the cookie. If it is not set, it defaults to the duration of the session, the session, which is when the cookie is removed when the client is shut down. Expires is used to specify a specific expiration time, and max-age sets the number of seconds in seconds to expire. If this value is 0, the cookie will be deleted. If this value is negative, the cookie file will not be generated. Max-age has a higher priority.
6. HttpOnly
Cookies with HttpOnly attributes cannot be retrieved by JS code, which means they cannot be retrieved by the browser console using document. Cookie, so this is a security measure that can effectively prevent XSS attacks.
7. Secure
This is the security attribute of cookies. Cookies marked as Secure can only be sent to the server through ENCRYPTED REQUESTS written in HTTPS. In this way, cookies cannot be stolen or tampered with during transmission between the browser and the server, preventing HTTP hijacking.
8. SameSite
This attribute is used to limit the sending scenario of third-party cookies. The value can be:
- Strict: Cookies are not sent under any circumstances in cross-site conditions.
- Lax: Default, no third-party cookies are sent except in the following three cases
- A label
- The link tag
- The method is a form request from GET
- None: All cross-sites are allowed to send cookies. If set to None, the Secure property must be enabled.
Advantages and disadvantages of Cookies
advantages
- High scalability and usability.
- Through encryption and secure transmission technology SSL, reduce the possibility of cookie cracking.
- You can configure the cookie life cycle so that even if the cookie is stolen, you get an expired cookie.
disadvantages
- The number of cookies under a specific domain name is limited. When the limit is exceeded, the browser will clear the cookies previously set.
- Cookie size is limited to 4KB.
- You need to encapsulate your own methods for getting, setting, and deleting cookies.
- There is a security issue, if a cookie is intercepted, the interceptor doesn’t need to decrypt the cookie, just forward the cookie to achieve some purpose.
- Some states cannot be saved on the client side.
- Cookies cannot be used across domains.
Does an HTTP domain name carry a cookie when it accesses an HTTPS domain name?
Cookies are not shared when Secure is set to true, but can be shared if they are not.
Why are cookies not secure?
Because cookies are stored on the browser, some criminals may intercept cookies through packet capture tools.
How do I solve the Cookie security problem?
- When setting the cookie validity period, try not to set it too long.
- Set the HttpOnly attribute to true. Preventing JAVASCRIPT scripts from reading cookie information prevents XSS attacks.
- Encrypt cookies.
- When a user logs in for the first time, the IP address and cookie are encrypted and saved as a token. Each request is encrypted by combining the cookie and IP address for comparison. Authentication succeeds only when the IP address corresponds to the IP address.
- Session and cookie are used together.
- Use HTTPS whenever possible.
Second, the Session
What is Session?
Session represents a Session between the server and the client. The Session object stores the properties and configuration information required for a specific user Session. In this way, when a user jumps between Web pages of the application, the variables stored in the Session object are not lost, but persist throughout the user Session. The session ends when the client closes the session or the session times out. The server implements the session using Cookies, which contain a session Id that the Web application pairs with its internal data and retrieves stored variables for use by the requested page.
How does Session differentiate users?
When the server receives the request for the first time, it creates a session space, creates a session object, generates a sessionId, and passes the response header set-cookie: Jsessionid = XXXX responds to the client, after receiving the response, the client will set the JsessionID in the cookie information of the local client, and then each time the client sends a request to the same website, the request header will carry the cookie information. This cookie information contains the sessionID, which the server uses to distinguish between different users.
What are the disadvantages of sessions?
If server A stores Session, after load balancing, server A may forward user requests to server B, but server B does not store Session of server A, which will lead to Session invalidity.
The difference between Session and Cookie
- Cookie data is stored on the client, and session data is stored on the server.
- Cookies are less secure than sessions because they are stored on the client.
- Session is stored on the server. If the number of accesses increases, the performance of the server will be reduced.
- The size of data stored in a single cookie cannot exceed 4K. Many browsers limit the number of cookies that can be stored. The amount of data stored in a session may be higher than that stored in a cookie.
- Session implementation depends on cookies, and the session ID needs to be stored in cookies.
- The validity period varies. Cookies may be set to be saved for a long time, but sessions generally have a short validity period. The client is shut down or the session times out.
Third, sessionStorage
What is the sessionStorage?
SessionStorage is a new sessionStorage object in HTML5. It is used to temporarily store the data of the same window or TAB. After closing the window or TAB, the data will be deleted.
SessionStorage refresh browser lost?
SessionStorage data only exists in the current browser TAB page, the same page in another TAB page is a different storage, data is still retained after page refresh, even if you use forced refresh, sessionStorage still exists. However, closing or re-opening the browser TAB will not be retained. If a TAB contains multiple iframe tags and they belong to the same page, they can share the sessionStorage between them.
SessionStorage Can two tabs share?
In the browser a TAB represents a session, two different tabs, sessionStorage does not share.
Does sessionStorage still exist after a jump from the same TAB?
In the same TAB, if you use target=”_blank” mode to jump, the previous page sessionStorage can be brought back.
Fourth, the LocalStorage
What is the LocalStorage?
LocalStorage is one of the apis of HTML5 LocalStorage web storage features. It is essentially a hash table, which exists in the browser. It is used to save a large amount of data in the browser. In addition, it is stored only on the client and does not communicate with the server. LocalStorage is restricted by the same origin policy, and the final storage form of key-value pairs is a string.
LocalStorage Specifies the storage mode
- The data is stored using the setItem method, which takes two parameters, the key name and the saved data.
localStorage.setItem("key"."value");
Copy the code
- The data is read using the getItem method.
localStorage.getItem("key");
Copy the code
Does LocalStorage exist across domains?
LocalStorage is restricted by the same origin policy, which causes cross-domain problems.
LocalStorage How to set the expiration time?
LocalStorage itself does not provide expiration, so we can give the prototype object to add a method to realize the expiration time Settings, set the value of the current record in time, then the value of time for a judgment, whether in before the current time and time within the specified range, if the above is to empty the current item, And returns NULL, which cannot be an object when set and needs to be converted to a string via json.stringify.
Cookie and LocalStorage and SessionStorage
Life cycle differences
- Cookie: You can set the expiration time. If you do not set the expiration time, the browser will expire after closing by default.
- LocalStorage: will be permanently saved unless manually cleared.
- SessionStorage: valid only in the current session web page, will be cleared when the page or browser is closed.
Storage capacity difference
- The size of the cookie stores data is about 4KB.
- LocalStorage and sessionStorage can hold up to 5MB of information.
The difference between communication with the server
- Cookie: Each communication with the server is carried in the HTTP header. Using cookies to save too much may cause performance problems.
- LocalStorage and sessionStorage: stored only in the client and do not communicate with the server.
Different ease of use
- Cookie: The native cookie interface is unfriendly and requires the programmer to encapsulate it.
- LocalStorage and sessionStorage: Native interfaces can be accepted or reencapsulated.
reference
Thank you very much for the excellent articles provided by the following bloggers.
- Cookie, Session, Token, JWT