A: cookit

1) What is cookit?

Is a small piece of data that the server sends to the user’s browser and keeps locally, which is carried and sent to the server the next time the browser makes a request to the same server.

2) 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 in the form of cookies for each subsequent request.

3) timely
  • If theSet-CookieNot throughExpries,Max-AgeTwo field SettingsCookieTimeliness, so thisCookieIt’s a simple onePhase session cookies. It is automatically deleted when the browser is closed.
  • If you set it upExpries,Max-AgeThen thisCookieIs valid for a specified period of time.

Note: Note: When Cookie expiration time is set, the date and time are only relevant to the client, not the server.

5) scope

The Domain and Path identifiers define the scope of the Cookie: that is, which urls the Cookie should be sent to. The Domain identifier specifies which hosts can accept cookies. If this parameter is not specified, it defaults to the host of the current document (excluding the subdomain name). If Domain is specified, subdomain names are generally included.

The Path identifier specifies which paths under the host can accept cookies (the URL Path must exist in the request URL). Child paths are also matched with the character %x2F (“/”) as the path separator.

6) Storage size
  • cookie: The value of a single cookie cannot exceed4kb;
  • sessionThere is no limit to size.
7) the characteristics of the cookie

Advantages:

  • Store user information (user token)
  • Marking user behavior (UUID, buried point)

Disadvantages:

  • CookieWill be attached to eachHTTPRequest, so virtually increased traffic
  • CookieMay be disabled. When a user is very privacy conscious, he is likely to disable the browserCookieFunction;
  • Due to theHTTPIn the requestCookieIt’s in plain text, potential security risks,CookieIt could be tampered with
  • eachCookieLength cannot exceed4KB
8) Cookie security issues

<1>: XSS and defense XSS

  • XSS (cross-site scripting attack):

Malicious attackers insert malicious script code into web pages. As the user browses the page, the script code embedded in the Web page is executed, thus enabling malicious attacks on the user.

  • Prevention:
    • Cookie Security Policy

    The server sideWhen setting cookies, set http-only to prevent users from obtaining cookies through JS. Generally, the following fields are set:

    1. http-only: only allowhttporhttpsRequest to readcookie,JSThe code is unreadablecookie(document.cookieWill be displayedhttp-onlythecookieItems are automatically filtered out. Automatically sent when the request is sentcookie.
    2. secure-only: only allowhttpsRequest read, automatically sent when sending a requestcookie.
    3. host-only: Allows only host domain names anddomainOnly the websites whose Settings are consistent can be accessedcookie.
    • XSS defends against HTML encoding

    Coding rule: will& < > "' /Escape to entity characters. The basic escape code is as follows:

    <! DOCTYPE html> <html> <head> <meta charset=utf-8> <meta name="referrer" content="never"> <title></title> </head> <body> Function htmlEncodeByRegExp(STR) {var s ="; if (str.length === 0) { return s; } return (s + str) .replace(/&/g, "&") .replace(/</g, "<") .replace(/>/g, ">") .replace(/ /g, " ") .replace(/\'/g, "&#39") .replace(/\"/g, """) .replace(/\//g, '&#x2F; '); Function htmlDecodeByRegExp(STR) {var s = "; if (str.length === 0) { return s; } return (s + str) .replace(/&/g, "&") .replace(/</g, "<") .replace(/>/g, ">") .replace(/ /g, " ") .replace(/&#39/g, "\'") .replace(/"/g, "\"") .replace(/&#x2F; /g, "\/"); } var HTML = '<br>aaaaaa<p> XXXXXX </p>'; var encodeHtml = htmlEncodeByRegExp(html); // Output: encode HTML with regular expressions: <br>aaaaaa<p> XXXXXX <&#x2F; P > console.log(" Encoding HTML using regular expressions: "+ encodeHtml); var decodeHtml = htmlDecodeByRegExp(encodeHtml); <br>aaaaaa<p> XXXXXX </p> console.log(" decodeHtml with regular expressions: "+ decodeHtml); </script> </body> </html>Copy the code
    • XSS defends against HTML Attribute encoding
    • Javascript encoding for XSS defense

<2> CSRF and CSRF defense

  • CSRF: Cross-site request forgery (CSRF) is an attack that impersonates a trusted user to send an unexpected request to a serverCSRF(Cross-site Request Forgery)The Chinese name is cross-site request forgery. So what is cross-site request forgery? When a user logs in to a normal website, they don’t log out of the normal website,cookieThe information remains, but when the user clicks on a dangerous site, the dangerous site can retrieve the one you logged on tocookieInformation. Then use thecookieInformation to do something else
  • CSRF precautions
    • strict: the browser does not carry it in any cross-domain requestCookieThis can be an effective defenseCSRFHowever, when a website with multiple subdomain names uses the main domain name to store user login information, users need to re-log in to each subdomain name, resulting in poor user experience.
    • The cookie validity period is set
    • To prevent cookies from being plaintext, the server generates key authentication
    • Generate random numbers and cookies and send them to the server

2: the Session

1) What is session?

Session represents a Session between the server and the client

2) create the session

A Session is automatically created when a user accesses the server for the first time. Note that a Session is created only when accessing programs such as JSPS and servlets, but not when accessing static resources such as HTML and IMAGE. If a Session has not already been generated, you can also use request.getSession(true) to force a Session to be generated.

First Creation SessionThe server will be in theHTTPThe protocol tells the client that theCookie Record one in there SessionIDFor each subsequent request, use this sessionIDSend it to the server, and I’ll know who you are.session Run dependency ofSessionIDAnd theSessionIDThere is acookieIn the.

3)Session validity period

As more and more users access the server, more and more sessions are created. To prevent memory overflow, the server removes sessions that have not been active for a long time from memory. This time is the Session timeout. If the server is not accessed after the timeout period, the Session is automatically invalidated.

  • SessionThe timeout period of ismaxInactiveIntervalAttribute, which can be passed by the correspondinggetMaxInactiveInterval()Get, passsetMaxInactiveInterval(longinterval)Modification.
  • SessionYou can also change the timeout in web.xml. Also, by callingSessiontheinvalidate()Methods that enableSessionFailure.

There are three ways to invalidate a Session:

  • The server unexpectedly shuts down. (When the server is normally shut downsessionIs stored on the server by the serversession.serIn files (under Work folder)
  • sessionSuicide: callsession.invalidate()Method can kill instantlysession;
  • It can be in the web.xml file under the server<session-timeout> 30 </session-timeout>Change this to the default value (default 30 minutes) in minutes.

.

4) Does the session expire when the browser is closed?
  • Why does it fail?
    • Generated on the server sidesessionAnd thesessionidthroughset-cookieAfter being sent to the browser, every request except the image and static file request will be written to the browser by the servercookie
    • The server receives the packetsessionidThrough thesessionidFind the correspondingsessioninformation
    • Set in the current domain name when the browser is closedcookieWill be empty
    • The next request is received by the serversessionfornullThe server considers the current user to be a new user and logs in again or directly sets a new usersessionid

That’s why sessions expire when the browser closes.

  • How do you keep it from failing?

    • inSet-CookieSet whenExpriesorMax-Age, is actually settingCookieThe failure time of. Or you can just putSessionidStore it locally.

Three: web Storage

Web Storage APIProvides a mechanism to enable the browser to be used in a ratioCookieA more intuitive way to store key/value pairs.Web Storage has the following two mechanisms:

  • sessionStorageFor each given source(given origin)Maintains a separate storage area that is available for the duration of a page session (that is, as long as the browser is open, including page reloads and resumes).
  • localStorageSame functionality, but data remains after the browser closes and then opens again.
1) the same
  • Generally, the storage size is about 5M
  • They are restricted by the same Origin policy and cannot be accessed across domains
  • Data is stored only in the client and does not participate in communication with the serverhttp Request sent to the server)
  • In order tokeyvalue To store data in the form of,valueThe value must be a string, otherwise it will be automatically converted (valueIf it is an object, it needs to be convertedjsonStore it)
2) No similarities
  • The life cycle

    • Data stored by localStorage is permanent and will persist unless manually deleted by the user (by invoking the localStorage API or wiping browser data).

    • Data stored in sessionStorage will be deleted at the end of the current session, once the window or TAB is closed, then all data stored in sessionStorage will be deleted.

  • scope

    • LocalStorage: In the same browser, same-origin documents share localStorage data, which can be read, overwritten, and erased from each other (same browser restriction, same-origin restriction).

    • SessionStorage: The same browser source document requirement as localStorage. In addition, the scope of sessionStorage is limited to Windows, that is, only same-origin documents of the same browser and the same window can share data (same-browser restriction, same-origin restriction, same-tab restriction).

3) operation

SessionStorage localStorage has no difference in operation. The following uses sessionStorage as an example:

  • Add and modify

    • Add and modify data using setItem
    sessionStorage.setItem('name', 'qianyin');
    sessionStorage.setItem('name', 'linheng');
    sessionStorage.setItem('user1', {name: 'qianyin'});
    sessionStorage.setItem('user2', JSON.stringify({name: 'qianyin'}));
    
    Copy the code
    • Add and modify data in the form of objects
    sessionStorage.name = 'qianyin';
    sessionStorage.name = 'linheng';
    sessionStorage.user1 = {name: 'qianyin'};
    sessionStorage.user2 = JSON.stringify({name: 'qianyin'})
    
    Copy the code
  • To get the data

    • Get the data by getItem
    sessionStorage.getItem('user')
    
    Copy the code
    • Get data in the form of objects
    sessionStorage.user
    Copy the code
  • To remove data

    • Removes specified data by removeItem
    sessionStorage.removeItem('user');
    Copy the code
    • Removes specified data as an object
    delete sessionStorage.user
    
    Copy the code
    • Removes all data in the current scope
    sessionStorage.clear();
    
    Copy the code