Session tracing is a common technique used in Web applications to track a user’s entire Session. Common Session tracking techniques are cookies and sessions. Cookies identify users by recording information on the client, and sessions identify users by recording information on the server.

A, Cookie,

HTTP is a stateless protocol. Once the data exchange is complete, the connection between the client and server is closed and a new connection needs to be established to exchange data again. This means that the server cannot track the session from the connection. That is, the server cannot determine whether the purchase belongs to user A’s session or user B’s session when user A purchases an item and places it in the shopping cart. To trace this session, a mechanism must be introduced.

Cookies are one such mechanism. It can compensate for the stateless HTTP protocol. Before sessions, almost all websites used cookies to track sessions.

1.1. What is Cookie?

Because HTTP is a stateless protocol, the server has no way of knowing the identity of the client from the network connection alone. What to do? Just issue a pass to the clients, one for each, and whoever accesses must bring their own pass. So the server can identify the client from the pass. That’s how cookies work.

A Cookie is actually a small piece of text information. The client requests the server, and if the server needs to record the user state, it issues a Cookie to the client browser using response. The client browser saves the Cookie. When the browser requests the site again, the browser submits the requested URL along with the Cookie to the server. The server checks the Cookie to identify the user’s state. The server can also modify the contents of the Cookie as needed.

Note: Cookie functionality requires browser support. Cookies are disabled if browsers don’t support them (as they do on most phones) or disable them. Different browsers save cookies in different ways.

1.2. Non-transdomainability

Many websites use cookies. For example, Google issues cookies to clients, Baidu also issues cookies to clients. Will the browser visit Google also carry the Cookie issued by Baidu? Or can Google modify cookies issued by Baidu?

The answer is no. Cookies are not cross-domain. According to the Cookie specification, the browser will only carry Google’s Cookie when visiting Google, but not Baidu’s Cookie. Google can only operate Google’s Cookie, but not Baidu’s Cookie.

Cookies are managed by the browser on the client side. The browser can guarantee that Google will only operate Google’s Cookie and not Baidu’s Cookie, so as to ensure the privacy security of users. The browser determines whether a web site can operate cookies on another web site based on the domain name. The domain name of Google and Baidu is different, so Google cannot operate Baidu’s Cookie.

Normally, cookies cannot be exchanged between two level 2 domains under the same level 1 domain, such as www.google.com and images.google.com, because the two domains are not strictly the same. If you want all secondary domain names under google.com to use the Cookie, you need to set the domain parameters of the Cookie.

Cookie cookie = new Cookie("time","20200000"); // Create a Cookie cookie.setDomain(".google.com"); // Set the domain cookie.setPath("/"); // Set the path cookie.setmaxage (integer.max_value); Response.addcookie (cookie); // Output to the clientCopy the code

Domain parameters must start with a dot (“.”). In addition, two cookies with the same name but different domains are two different cookies. If you want two websites with completely different domain names to share cookies, you can generate two cookies with two domain names and output them to the client.

The value of the Cookie. If the value is a Unicode character, you need to encode the character. If the value is binary data, BASE64 encoding is required.

1.3. Common Attributes

In addition to name and value, cookies have several other commonly used attributes. Each property corresponds to a getter and a setter.

The validity of 1.4.

The Cookie’s maxAge determines the Cookie’s validity period in seconds. Cookie through getMaxAge() method and setMaxAge(int maxAge) method to read and write the maxAge attribute.

If the maxAge attribute is positive, it means that the Cookie will automatically expire after maxAge seconds. The browser will persist cookies with a positive maxAge value, that is, write them to the corresponding Cookie file. The Cookie remains valid when the customer logs in to the website, regardless of whether the browser or computer is closed, as long as it is before maxAge seconds. The Cookie information in the following code is always valid.

Cookie cookie = new Cookie("username","helloweenvsfei"); // Create a Cookie cookie.setmaxage (integer.max_value); // Set the lifecycle to MAX_VALUE Response.addcookie (cookie); // Output to the clientCopy the code

If maxAge is negative, it means that the Cookie is valid only in the browser window and the child Windows opened by the browser window, and the Cookie becomes invalid after the window is closed. Cookies whose maxAge is negative are temporary cookies that will not be persisted and written to Cookie files. Cookie information is stored in browser memory, so the Cookie disappears when the browser is closed. The default maxAge value for cookies is -1.

If maxAge is 0, the Cookie is deleted. The Cookie mechanism does not provide a method to delete the Cookie. Therefore, the Cookie can be immediately invalidated to achieve the effect of deleting the Cookie. Invalid cookies are deleted from the Cookie file or memory by the browser.

Note: When cookies are read from the client, other attributes, including maxAge, are unreadable and will not be committed. The browser only submits the name and value attributes when submitting cookies. The maxAge attribute is only used by the browser to determine whether a Cookie is expired.

Be sure to set the expiration time, or the browser will close and disappear.

1.5. Modify/Delete

Cookies do not provide modification or deletion operations. If you want to delete a Cookie, you only need to create a Cookie with the same name, set maxAge to 0, and add it to Response to override the original Cookie. Notice it’s 0, not negative. Negative numbers mean something else. The reader can verify the above example by setting different properties.

Note: When modifying or deleting cookies, all attributes of the new Cookie except value and maxAge, such as name, path and domain, must be exactly the same as the original Cookie. Otherwise, the browser will not overwrite the cookies as two different cookies, resulting in the modification and deletion failure.

1.6. The path

The identifier specifies which paths under the host can accept cookies, and the child paths will be matched.

For example, if only programs under /hello/ are allowed to use cookies, we could write:

cookie.setPath("/hello/"); // Set the pathCopy the code

/ allows all paths to use cookies. The path attribute needs to end with a slash. Two cookies with the same name but the same domain are also two different cookies.

Note: a page can only get cookies of the Path to which it belongs. For example, /hello/test/a.html cannot get cookies with path /hello/ ABC /.

1.7. Safety

The HTTP protocol is not only stateless, it is also insecure. HTTP data is transmitted directly on the network without any encryption and may be intercepted. Using THE HTTP protocol to transfer very confidential content is a danger. If you do not want cookies to be transmitted over non-secure protocols such as HTTP, you can set the secure attribute of cookies to true. Browsers only transmit such cookies over secure protocols such as HTTPS and SSL.

cookie.setSecure(true);
Copy the code

The secure property does not encrypt the content of the Cookie and therefore does not guarantee absolute security. If high security is required, the Cookie content needs to be encrypted and decrypted in the program to prevent disclosure.

Second, the Session

Session is a mechanism used by the server to record the status of the client. It is simpler to use than cookies, which increases the storage pressure of the server.

2.1. What is Session?

Session is another mechanism for recording the client’s state, except that cookies are stored in the client browser, while sessions are stored on the server. When the client browser accesses the server, the server records the client information in some form on the server. So that’s Session. The client browser only needs to look up the client’s status from the Session when revisiting.

If the Cookie mechanism determines the identity of a customer by checking the “pass” on the customer, the Session mechanism determines the identity of the customer by checking the “customer list” on the server. A Session is a client file created by the program on the server. When a client visits the server, it only needs to query the client file table.

Corresponding class Session for javax.mail. Servlet. HTTP. HttpSession class. Each visitor corresponds to a Session object, in which all state information about that client is stored. The Session object is created when the client first requests the server. Session is also a key-value attribute pair. The getAttribute(Stringkey) and setAttribute(String Key, Objectvalue) methods are used to read and write customer status information. The client’s Session is obtained in the Servlet using the request.getSession() method.

If the client Session does not exist, the request.getSession() method returns null, and getSession(True) creates the Session before returning it.

HttpSession session = request.getSession(); // Get the Session object session.setAttribute("loginTime", new Date()); Println ("loginTime: "+(Date) session.getattribute ("loginTime")); // Get the Session attributeCopy the code

When multiple clients execute a program, the server saves sessions for multiple clients. You don’t have to declare whose Session you’re retrieving. The Session mechanism determines that the current client can only obtain its own Session, but not others’ Session. Each client’s Session is also independent of each other.

Session is more convenient than Cookie. However, too many sessions are stored in the server memory, causing stress on the server.

2.2. Life cycle

The Session is stored on the server side. For faster access, servers typically store sessions in memory. Each user will have a separate Session. If the Session content is too complex, it can cause memory overflow when a large number of clients access the server. Therefore, the information in the Session should be as minimal as possible.

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.

After a Session is generated, the server updates the last access time of the Session and maintains the Session as long as the user continues to access the Session. Each time a user accesses the server, regardless of whether the user reads or writes a Session, the server considers that the user’s Session is active.

The validity of 2.3.

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.

The Session timeout period is maxInactiveInterval. You can obtain the value from getMaxInactiveInterval() and change it from setMaxInactiveInterval(longInterval).

Session timeout can also be changed in web.xml. Alternatively, you can invalidate a Session by calling its invalidate() method.

2.4. Common methods

The default Session timeout period in Tomcat is 20 minutes. Run setMaxInactiveInterval(int seconds) to change the timeout period. You can modify web. XML to change the default Session timeout. For example, change it to 60 minutes:

<session-config> <! </session-timeout> </session-config>Copy the code

2.5. Browser requirements

Although the Session is held on the server and transparent to the client, it still requires the client’s browser to function properly. This is because a Session needs to use a Cookie as an identifier. The HTTP protocol is stateless and a Session cannot be identified as the same client based on the HTTP connection. Therefore, the server sends a Cookie named JSESSIONID to the client browser with the Session ID (the return value of httpsession.getid ()). The Session uses this Cookie to identify whether the user is the same.

The Cookie is automatically generated by the server, and its maxAge attribute is generally -1, indicating that the Cookie is valid only within the current browser, and is not shared between browser Windows, and the browser will be invalid after closing.

So when two browser Windows on the same machine access the server, two different sessions are generated. New Windows opened by links, scripts, etc. (that is, Windows not opened by double-clicking the desktop browser icon, etc.) are excluded. Such child Windows share the parent window’s Cookie and therefore share a Session.

Note: Newly opened browser Windows generate new sessions, except for child Windows. Child Windows share the parent window’s Session. For example, when you right-click on the link and select “Open in A New window” from the pop-up shortcut menu, the child window can access the Session of the parent window.

What if the client browser disables cookies or does not support cookies? For example, most mobile browsers don’t support cookies. The Java Web provides another solution: URL address rewriting.

2.6. URL Address rewrite

URL address rewriting is a solution that does not support cookies for clients. The PRINCIPLE of URL address rewriting is to rewrite the USER Session ID into the URL address. The server can parse the rewritten URL to get the Session ID. This allows sessions to record user status even if the client does not support cookies. The HttpServletResponse class provides encodeURL(Stringurl) to implement URL rewriting, for example:

<td> <a href="<%=response.encodeURL("index.jsp? c=1&wd=Java") %>"> Homepage</a> </td>Copy the code

This method automatically determines whether the client supports cookies. If the client supports cookies, the URL is printed intact. If the client does not support cookies, the user Session ID is overwritten into the URL. The rewritten output might look like this:

<td> <ahref="index.jsp; jsessionid=0CCD096E7F8D97B0BE608AFDC3E1931E? c= 1&wd=Java">Homepage</a> </td>Copy the code

Add the string “after the file name and before the URL parameter; Jsessionid = XXX “. XXX is the Session ID. Analysis shows that the addition of the JsessionID string does not affect either the file name of the request or the address bar parameters of the submission. When the user clicks this link, the Session ID is submitted to the server through the URL, and the server obtains the Session ID by parsing the URL.

If the page is redirected, the URL can be rewritten like this:

< % if (the "administrator". The equals (userName)) {response. SendRedirect (response. EncodeRedirectURL (" administrator. JSP ")); return; } % >Copy the code

The effect is the same as response.encodeURL(String URL) : if the client supports cookies, the original URL is generated; if the client does not support cookies, the rewritten address with jsessionID String is returned.

As for WAP applications, since most mobile browsers do not support cookies, WAP applications use URL rewriting to track user sessions. For example, the mobile business street of yonyou Group.

Note: TOMCAT determines whether the client browser supports cookies based on whether the request contains cookies. Although the client may support cookies, since no cookies are carried on the first request (because there are no cookies to carry), the URL address rewritten will still have a JsessionID in the address. The server has already written a Cookie to the browser on the second visit, so the rewritten URL does not have a JsessionID in it.

2.7. Do not use cookies

Since most client browsers on WAP do not support cookies, it would be better to disable the Session from using cookies. The Java Web specification supports configuring cookies to be disabled. Here is an example of how to disable cookies through configuration.

Open the meta-INF folder in the WebRoot directory of the sessionWeb project (the same as the web-INF folder, if not created), open context. XML (if not created), and edit the following:

<? The XML version = '1.0' encoding = "utf-8"? > <Context path="/sessionWeb" cookies="false"> </Context>Copy the code

Or modify the Tomcat global conf/context. XML file as follows:

<! -- The contents of this file will be loaded for eachweb application --> <Context cookies="false"> <! -... </Context>Copy the code

After deployment, TOMCAT does not automatically generate cookies named JSESSIONID, and sessions are not identified by cookies, but by rewritten URLS.

Note: This configuration only disallows the Session from using cookies as identifiers, and does not prevent other cookies from reading and writing. This means that the server does not automatically maintain cookies named JSESSIONID, but the application can still read and write other cookies.

Third, the difference between cookie and session

  1. Cookie data is stored on the client’s browser and session data is stored on the server.

To put it simply, when you log into a website, if the Web server is using a session, then all the data is stored on the server,

Each time the client requests the server, it will send the session_ID of the current session. According to the current session_ID, the server determines the corresponding user data flag to determine whether the user is logged in or has certain permissions.

Since the data is stored on the server, you can’t fake it, but if you can get the session_ID of a logged-in user, you can still fake that user’s request with a special browser.

Session_id is assigned randomly when the server and client link. Generally there is no duplication, but if there is a large number of concurrent requests, it is not without the possibility of duplication.

A Session is a storage space on the server maintained by the application server. When users connect to the server, the server generates a unique SessionID and uses the SessionID as an identifier to access the Session storage space on the server. The SessionID data is saved to the client using cookies. When the user submits the page, the SessionID will be submitted to the server to access the Session data. This process is done without developer intervention. So once the client disables the Cookie, the Session is also invalidated.

The Session information is stored on the server, but the Session ID is stored in the cookie of the client. Cookies are kept completely on the client side.

  1. Cookies are not very secure, so someone can analyze cookies that are stored locally and do cookie spoofing and you should use sessions for security purposes. Cookies are not secure, but they can be encrypted.

  2. Cookie expiration is enabled by setting the cookie time. But with session-destory (), we will destroy the session.

  3. Sessions are stored on the server for a certain amount of time. Cookies should be used to reduce server performance when the number of accesses increases.

  4. A single cookie can hold no more than 4K of data, and many browsers limit a site to 20 cookies (Session objects have no limit on how much data can be stored and can hold more complex data types).

  5. Sessions are easy to fail and the user experience is poor.

The biggest difference between the two is the lifetime between IE startup and IE shutdown (the session disappears as soon as the browser page is closed) and the preset lifetime, or permanently stored in a local file. (cookies).

Fourth, cross-domain

4.1. Why do cross-domain problems occur

The same origin policy is restricted by the browser.

For example, the front-end project is deployed on server A and the back-end project is deployed on server B. If you access the front-end page of server A, clicking the button on the page will access the resources of server B, and cross-domain occurs.

Note: For cross-domain requests, the server can respond normally, but the browser hijacked the data when it returned to the browser.

4.2. Same-origin policy

The Same-Origin Policy is a convention. It is the core and most basic security function of a browser. If the Same-Origin Policy is absent, the normal functions of the browser may be affected. The Web is built on the same origin policy, and browsers are just an implementation of the same origin policy. The same origin policy prevents javascript scripts in one domain from interacting with content in another domain. Same-origin (that is, in the same domain) means that two pages have the same protocol, host, and port.

Tags such as A, IMG, script, link, iframe, video, and audio are not restricted by the same Origin policy.

4.3. Cross-domain solution

CORS stands for Cross-Origin Resource Sharing. It is a W3C standard and a fundamental solution for cross-source AJAX requests.

There are two solutions:

  • Normal cross-domain request: the server only needs to set the response headerAccess-Control-Allow-Origin, telling the browser that this is a request that allows cross-domain access. Although the implementation of CORS requires both client and server support, most browsers support it (IE at least version 10).
  • Cross-domain request with cookie: Both the front and back ends need to be set

This front end

Determine whether cookies are present based on the xhr.withCredentials field.

  1. Native ajax
var xhr = new XMLHttpRequest(); // Ie8/9 requires window.XDomainRequest compatibility // The front end is set to whether the cookie xhr.withCredentials = true; xhr.open('post', 'http://www.domain2.com:8080/login', true); xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); xhr.send('user=admin'); xhr.onreadystatechange = function() { if (xhr.readyState == 4 && xhr.status == 200) { alert(xhr.responseText); }};Copy the code
  1. jQuery ajax
$.ajax({ url: 'http://www.test.com:8080/login', type: 'get', data: {}, xhrFields: { withCredentials: CrossDomain: true, // the request header contains additional cross-domain information, but does not contain cookies});Copy the code
  1. vue-resource
Vue.http.options.credentials = true
Copy the code
  1. axios
axios.defaults.withCredentials = true

Copy the code

4.3.2. The service side

Server support for CORS is mainly through setting access-Control-Allow-Origin. If the browser detects the Settings, Ajax can be allowed to access across domains.

/ * * import packages: import javax.mail. Servlet. HTTP. HttpServletResponse; HttpServletResponse Response */ / allow cross-domain access domain name: SetHeader (" access-Control-allow-origin ", "http://www.domain1.com"); response.setHeader(" access-Control-allow-origin ", "http://www.domain1.com"); // Allow front-end authentication cookies: When this item is enabled, the domain name cannot be '*', and the specific domain name must be specified. Otherwise, the browser displays response. SetHeader (" access-Control-allow-credentials ", "true"); Responsetheader (" access-Control-allow-headers ", "content-type, x-requested-with "); response.setHeader(" access-Control-allow-headers "," content-type, x-requested-with ");Copy the code

For more articles in this series, please pay attention to wechat official account [1024 Planet].