A comprehensive analysis of security and protocol [] cookies, session, sessionStorage and contrast localStorage

View data stored in the browser

Here Insert Picture Description

HTML4 local cookie store

The browser's caching mechanism can provide a way to store user data on the client, it can exchange data using the cookie, session and so on with the server.

A, cookie and session

cookie and session are used to track the user's identity conversational mode browser.

the difference:

  1. Hold: cookie stored in the browser, session stored on the server side

  2. Use:
    ① cookie mechanism: If your browser is not set an expiration time, the cookie is stored in memory, along with the life cycle of closing the browser and the end of this short session cookie cookie. If you set the expiration time of the cookie in the browser, the cookie is stored in the hard disk after you close your browser, cookie data still exists until the end of the expiration time to disappear.

    Cookie is a special information server to the client, cookie text is stored in the client's way, and carry it in every request

    ② session mechanism: When the server receives a request need to create a session object, it first checks the client request contains sessionid. If there sessionid, the server returns the corresponding session object based on the id. If the client does not request sessionid, the server creates a new session object and sessionid returned to the client in this response.

    Usually stored sessionid cookie to the client browser in accordance with the rules sessionid sent to the server in the interaction. If the user disables cookie, will have to use URL rewriting can be achieved by response.encodeURL (url); API to end encodeURL is, when the browser supports Cookie, url without any treatment; when the browser does not support (or users disabled) Cookie time, will rewrite the URL address to access SessionID after stitching.

  3. The stored content: cookie only store a string type to textually; to save the session by a similar data structure Hashtable, and can support any type of object (session may contain a plurality of objects)

  4. The size of the memory: cookie: single cookie stored data can not exceed 4kb; session is no size limit.

  5. Security: cookie: cookie exists for the attack: Cookie deception, Cookie intercepted; the security is greater than the session cookie.

    For the following reasons:
    (1) sessionID stored in a cookie, we must first break to break the session cookie;
    (2) sessionID to someone logs, or start session_start will have, so to break the cookie may not be able to get sessionID;
    (3) after starting session_start a second time, before once sessionID is ineffective, the session expires, sessionID also will fail.
    (4) sessionID is encrypted
    (5) In summary, the attacker would have to break the encryption in a short period of sessionID, it's hard.

  6. Scenario:

    the cookie:
    (1) determine whether the user landed website to enable automatic login next time (or remember the password) to log. If we delete the cookie, you have to log in every time to fill in the relevant information from the new login.
    (2) Last time save login information.
    Page (3) to save the last viewed
    (4) Browse counting
    Here Insert Picture Description
    the session:
    the Session for storing specific information for each user, the value of the variable is stored on the server side, to distinguish between different customers SessionID.
    (1) Online Shopping Mall in the cart
    (2) to save the user login information
    (3) certain data into the session, for different pages use the same user
    (4) to prevent users from unauthorized access

  7. Disadvantage:
    Cookie:
    (. 1) of limited size
    (2) the user can operate (disable) cookie, that the limited functionality
    (3) less secure
    (4) Some possible state stored in the client.
    (5) every access to the server sends a cookie, wasting bandwidth.
    (6) cookie concept of data path (path), you can limit the cookie belongs only under certain path.
    session:
    The more (1) Session save something, the more server memory footprint for large numbers of users online site, server memory pressure will be relatively large.
    (2) dependent on the cookie (sessionID cookie saved), if the cookie is disabled, will have to use URL rewriting, unsafe
    (3) create a Session variable has a lot of randomness, can be called at any time, developers do not need precise treatment, so excessive use of session variables will result in the code unreadable and poor maintenance.

HTML5 local storage

A, HTML5 local storage associated with two important content

Web Storage and a local database. Which, Web Storage is a storage mechanism for improvement in HTML4 cookie storage mechanism. Since the cookie storage mechanism has many drawbacks, HTML5 no longer use it, turn to the Web Storage storage mechanism improved. The local database is HTML5 in the new function, use it to build a database locally on the client, the original must save the contents of the server database can now be directly stored locally on the client, which greatly reduces the burden on the server side, but also accelerate the speed of access to data.

Second, explain the Web Storage

We know that the cookie can be used to save simple user information such as user names and other client in HTML4, but by long-term use, you will find that there is a permanent cookie stored data with the following questions:

  1. Size: cookie size is limited to 4KB.

  2. Bandwidth: cookie is being sent along with HTTP transactions, and therefore a waste of bandwidth to use when sending part of the cookie.

  3. Complexity: to correct cookie manipulation is very difficult.

To solve these problems, in HTML5, again offers the ability to save data locally on the client, it is the Web Storage.

The WebStorage offers two HTML5 API:

localStorage (local storage) and the sessionStorage (session storage)

  1. Life Cycle: localStorage: localStorage life cycle is permanent, after closing the page or browser data in localStorage will not disappear. localStorage unless the initiative to remove data, otherwise the data will never disappear.

sessionStorage life cycle is only valid in the current session. sessionStorage introduces the concept of a "browser window", sessionStorage is homologous window is always present in the data. As long as the browser window is not closed, even if refresh the page or go to another page homology, the data still exists. But sessionStorage will be destroyed after you close the browser window. Meanwhile a separate window open with the same page, sessionStorage is not the same.

  1. Storage size: localStorage sessionStorage size and storing data are generally: 5MB

  2. Storage location: localStorage and sessionStorage are stored in the client, not interactive communication with the server.

  3. Storing the content type: localStorage sessionStorage and only store string type, can be used for complex objects and parse JSON stringify ECMAScript object to provide a process

  4. 获取方式:localStorage:window.localStorage;;sessionStorage:window.sessionStorage;。

  5. Application scenarios: localStoragese: commonly used in long-term Log (+ determine whether the user is logged), suitable for long-term preservation of data locally. sessionStorage: single sign-sensitive account;

So far, more than Firefox3.6, Chrome6 above, Safari 5 or more, Pera10.50 above, IE8 or later browsers support the use of sessionStorage and localStorage.

Three, WebStorage advantages

(1) greater storage space: cookie is 4KB, and WebStorage is 5MB;

(2) to save network traffic: WebStorage not transmitted to the server, the data is stored locally can be directly obtained, it will not be as beautiful as the word cookie request will be sent to the server, reducing the interaction client and server, saving network flow;

(3) that only needs to keep a user during browsing a set of pages and can be discarded after closing the browser data, sessionStorage very convenient;

(4) fast display: On WebStorage, coupled with the browser's cache itself and some data storage. Can be acquired, the acquisition is faster than the faster from the server obtaining data from the local time;

(5) Safety: WebStorage not as HTTP header sent to the server, the security phase for the cookie, it is rather higher, do not worry intercepted, but there are still counterfeiting problem;

(6) WebStorage provides methods, data manipulation convenient than Cookie;

setItem (key, value) ——  保存数据,以键值对的方式储存信息。

getItem (key) ——  获取数据,将键值传入,即可获取到对应的value值。

removeItem (key) ——  删除单个数据,根据键值移除对应的信息。

clear () ——  删除所有的数据

key (index) —— 获取某个索引的key

cookies, sessionStorage and Comparative localStorage

Here Insert Picture Description

sessionStorage and localStorage using demo

First, a web page to save data and display data

<!DOCTYPE html>
<html>
    <head>
    <meta charset="UTF-8">
    <title>Web Storage 示例</title>
    </head>
    <body>
    <h1>Web Storage 示例</h1>
    <p id="msg"></p>
    <input type="text" id="input" />
    <input type="button" value="保存数据" onclick="saveStorage('input');" />
    <input type="button" value="读取数据" onclick="loadStorage('msg');" />
    </body>
</html>

When calling saveStorage method call when you click the "Save Data" button to save the data, click the "Read data" button loadStorage method call data, these two methods were in the script file script.js as follows:

//sessionStorage 示例  (保存一个会话周期:从打开浏览器——到关闭浏览器窗口)
function saveStorage(id){
    var target=document.getElementById(id);
    var str=target.value;
    sessionStorage.setItem("message",str);
    //或者sessionStorage.message=str;
}
function loadStorage(id){
    var target=document.getElementById(id);
    var msg=sessionStorage.getItem("message");
    //或者var msg=sessionStorage.message;
    target.innerHTML=msg;
}
//localStorage 示例(可永久保存)    
function saveStorage(id){
    var target=document.getElementById(id);
    var str=target.value;
    localStorage.setItem("message",str);
    //或者localStorage.message=str;
}
function loadStorage(id){
    var target=document.getElementById("msg");
    var msg=localStorage.getItem("message");
    //或者var msg=localStorage.message;
    target.innerHTML=msg;
}

The script files are used sessionStorage and localStorage two ways. Both methods are when the user typing text in the input box, click the "Save Data" button to save the data, click the "Read data" button to read the saved data. But not the same for both methods of handling data, when used sessionStorage method, if you close the browser, the data is lost, the next time the browser click the "Read data" button to open, read not see any data. When using localStorage method, even if the browser is closed, the next will still be able to read data stored when you open the browser. However, the data is stored in different browsers were saved, that is, open another browser is not read saved in this browser data.

A specific look at the basic method used to read and write data

(1)sessionStorage

Method to save the data:

sessionStorage.setItem("key","value");
//或者写成
sessionStorage.key="value";

Data reading method:

变量=sessionStorage.getItem("key");
//或者写成
变量=sessionStorage.key;

(2)localStorage

Method to save the data:

localStorage.setItem("key","value");
//或者写成
localStorage.key="value";

Data reading method:

变量=localStorage.getItem("key");
//或者写成
变量=localStorage.key;

Saving the data, if used sessionStorage reading or storing data and is used to read and write sessionStorage object and call the object's methods; localStorage if used to read or save data, is read using localStorage object and call the object's methods.

During read, regardless of which objects can be read by the data getItem method of that object may be custom property value reading data of the object; setItem method can save the data by the object, can also custom attribute value of the object data stored. In the form of "keys / key" is saved when you save the data. When reading data by getItem method of that object, the parameter is specified as keys, which returns the key; when the custom property value of the object by reading data, a custom property may be the name of the object as keys to access the custom property key attribute values ​​can be obtained; setItem method when the object data stored by the first argument specifies the name of a bond, is designated as the second key parameter; when by custom attribute values ​​of the object data is stored, a custom property may be the name of the object as keys, and then directly the custom property value is set to the key.

When you save the data does not allow duplicate key to save the same name. You can modify key save, but not modify keys (only to re-take the keys, and then save the key).

Finally, the results of this example is running in the browser as follows:

Here Insert Picture Description

Reference article

https://www.cnblogs.com/cencenyue/p/7604651.html

https://segmentfault.com/a/1190000007243675

https://www.zhihu.com/question/19786827

Published 134 original articles · won praise 80 · views 30000 +

Guess you like

Origin blog.csdn.net/Umbrella_Um/article/details/101648603