Cookie mechanism in the details
Cookie mechanism
In the program, session tracking is a very important thing. In theory, all request operations of a user should belong to the same session, and all the request operations of another user should belong to another session, and the two cannot be confused. For example, an item purchased by the user A in the supermarket should be placed in the shopping cart of the A, and no matter what time the user A purchases, they belong to the same session and cannot be placed in the shopping cart of the user B or the user C This does not belong to the same conversation.
Image: microsoft
Web applications use the HTTP protocol to transfer data. The HTTP protocol is a stateless protocol. Once the data exchange is completed, the client and server-side connections will be closed, the exchange of data again need to establish a new connection. This means that the server can not track sessions from the connection. That is, the user A purchases a product into the shopping cart, and when the product is purchased again, the server can not determine whether the purchasing activity belongs to the user A’s conversation or the user B’s conversation. To track the conversation, a mechanism must be introduced.
A cookie is one such mechanism. It can make up for the lack of stateless HTTP protocol. Before the advent of the session, basically, all websites used cookies to track conversations.
What is a cookie?
Cookie means “cookie,” a mechanism proposed by the W3C that was first developed by the Netscape community. Cookie has now become the standard, all of the major browsers such as IE, Netscape, Firefox, Opera and so support Cookie.
Because HTTP is a stateless protocol, servers simply do not know the identity of the client from the network connection. How to do it? It is the client who issued a permit it, a person, no matter who visits must bring their own passport. This server will be able to confirm the customer’s identity from the past. This is how cookies work.
A cookie is actually a short text message. The client requests the server to issue a cookie to the client browser using the response if the server needs to record the user’s status. The client browser will save the cookie. When the browser requests the website again, the browser submits the requested website along with the cookie to the server. The server checks the cookie to identify the user’s status and permissions. The server can also modify the contents of the cookie as needed.
Check out a website issued a cookie is very simple. In the browser address bar enter javascript:alert (document.cookie) on it (need to have a network to view).
Note: Cookie functionality requires browser support. If the browser does not support cookies (such as most mobile phones in the browser) or the cookie is disabled, the cookie function will expire. Different browsers use different ways to save cookies. IE will be in the “C:\Documents and Settings\your username\Cookies” folder to save the text file, a text file to save a cookie.
Cookie can not cross domain name
Many websites use cookies. For example, Google issues a cookie to the client and Baidu also issues a cookie to the client. That browser visit Google will also carry cookies issued by Baidu it? Or Google can modify Cookie issued by Baidu it?
the answer is negative. Cookies are not cross-domain. Under the cookie specification, browser access to Google will only carry Google’s cookies and will not carry Baidu’s cookies. Google can only operate Google’s cookies, but cannot operate Baidu’s cookies.
Cookies are managed by the browser on the client side. The browser can guarantee that Google will only operate Google’s cookies and will not operate Baidu’s cookies to ensure the privacy of users. Browser to determine whether a website can operate another website Cookie based on the domain name. Google and Baidu have different domain names, so Google can not operate Baidu’s cookies.
It should be noted that although the site https://images.google.com and the site https://www.google.com the same belong to Google the domain is not the same, both can not operate each other’s Cookie.
Note: The user logs into the website https://www.google.comYou will find that the login information is still valid when you access images.google.com, but ordinary cookies can not. This is because Google has done a special deal. Later in this chapter, cookies are also treated similarly.
Unicode encoding
Chinese and English characters are different, Chinese is a Unicode character, accounting for 4 characters in memory, while English belongs to ASCII characters, memory, only 2 bytes . Unicode characters need to Unicode characters in the cookie encoding, otherwise it will garbled.
Tip: Cookies can only be saved in Chinese encoding. UTF-8 encoding can be used generally. Not recommended GBK encoding such as Chinese, because the browser does not necessarily support, and JavaScript does not support GBK encoding.
BASE64 encoding
Cookies can not use only ASCII characters and Unicode characters, but also binary data. For example, using digital certificates in cookies provides security. It also needs to be encoded when using binary data.
Note: This program is only used to show that the cookie can store binary content, it is not practical. Because each time the browser requests the server to carry the cookie, the content of the cookie should not be too large, otherwise the speed of the cookie is affected. The content of cookies should be small and fine.
Set all the properties of the cookie
In addition to name and value, cookies also have several other commonly used attributes. Each property corresponds to a getter method and a setter method. All the properties of the Cookie class are shown in Table 1.1.
String name
The name of the cookie. Once created, the name of the cookie can not be changed
Object value
The value of this cookie. If the value is Unicode characters, character encoding is required. If the value is binary data, you will need to use BASE64 encoding
int maxAge
The cookie expires in seconds. If it is positive, the cookie expires after maxAge seconds. If it is negative, the cookie is a temporary cookie, closing the browser expires, and the browser does not save the cookie in any way. If 0, delete the cookie. The default is -1
boolean secure
Whether the cookie is only transmitted using secure protocols. Security Protocol. Security protocols such as HTTPS, SSL, etc., encrypt data before transmitting data over the network. The default is false
String path
The use of the cookie. If set to “/sessionWeb/“, only the program whose contextPath is “/sessionWeb/” can access the cookie. If set to “/”, the domain contextPath can access the cookie. Note that the last character must be “/”
String domain
The domain name that can access this cookie. If set to “.google.com”, all cookies ending in “google.com” will have access to this cookie. Note that the first character must be “.”
String comment
The usefulness of the cookie. The browser displays the cookie information is displayed when the instructions
int version
The version number used by this cookie. 0 means following Netscape’s cookie specification and 1 means following W3C’s RFC 2109 specification.
The validity of the cookie
Cookie’s maxAge determines the cookie’s expiration date, in seconds. The cookie uses the getMaxAge() method with the setMaxAge(int maxAge) method to read and write the maxAge property.
If the maxAge property is positive, then the cookie expires automatically after maxAge seconds. The browser will persist the cookie whose maxAge is positive, ie write it to the corresponding cookie file. Whether the client closes the browser or the computer, the cookie remains valid as long as it is still maxAge seconds before logging in to the site. Cookie information in the following code will always be valid.
Cookie cookie = new Cookie(“username”,”helloddos”);
cookie.setMaxAge(Integer.MAX_VALUE);
response.addCookie(cookie);
If maxAge is negative, the cookie is valid only in the browser window and the sub-window open in the window, the cookie expires after the window is closed. Cookies with maxAge negative are temporary cookies that are not persisted and will not be written to cookie files. Cookie information is stored in the browser memory, so close the browser the cookie disappears. The default maxAge value for cookies is -1.
If maxAge is 0, the cookie is deleted. The cookie mechanism does not provide a way to delete cookies, so delete the cookie by setting the cookie to expire immediately. The expired cookie will be removed from the cookie file or memory by the browser,
E.g:
Cookie cookie = new Cookie(“username”,”helloddos”);
cookie.setMaxAge(0);
response.addCookie(cookie);
The response object provides a cookie operation method is only one add operation cookie(cookie).
To modify the cookie can only use a cookie of the same name to overwrite the original cookie, to achieve the purpose of modification. Delete only need to modify maxAge to 0.
Note: Other properties, including maxAge, are unreadable and will not be committed when reading cookies from the client. When the browser submits the cookie, only the name and value attributes will be submitted. The maxAge property is only used by browsers to determine if cookies expire.
Changes, delete cookie
Cookie does not provide modify, delete operation. If you want to modify a cookie, only need to create a new cookie with the same name, added to the response to overwrite the original cookie.
If you want to delete a cookie, just create a new cookie with the same name, set maxAge to 0, and add the response to overwrite the original cookie. Note that it is 0 instead of negative. Negative numbers represent other meanings. Readers can verify the procedure through the above example, set different properties.
Note: When modifying or deleting cookies, all attributes except new value maxAge, such as name, path, domain, etc. should be exactly the same as the original Cookie. Otherwise, the browser will treat it as two different cookies will not be covered, resulting in modification, deletion failed.
Cookie’s domain name
Cookies are not cross-domain. Domain name https://www. google.com Issued Cookie will not be submitted to the domain name Bing, you know to go with. This is determined by the cookie’s privacy security mechanism. Privacy safeguards prevent websites from illegally obtaining cookies from other websites.
Under normal circumstances, the same level two domain name domain name https://securityonline.info Cookies can not be used interchangeably with images.helloddos.com because the domain names are not exactly the same. If you want all the helloddos.com second-level domain name can use the cookie, you need to set the cookie’s domain parameters, for example:
Cookie cookie = new Cookie(“time”,”20080808″);
cookie.setDomain(“.https://securityonline.info”);
cookie.setPath(“/”);
cookie.setMaxAge(Integer.MAX_VALUE);
response.addCookie(cookie);
Readers can modify the native C:\WINDOWS\system32\drivers\etc hosts file to configure multiple temporary domain names, and then use the setCookie.jsp program to set cross-domain Cookie validation domain attributes.
Note: The domain parameter 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 totally different domain names to share cookies, you can generate two cookies. The domain attributes are two domain names and output to the client.
Cookie path
The domain attribute determines the domain name where the cookie is run, and the path attribute determines the path to the cookie (ContextPath). For example, if you allow only programs under / sessionWeb / to use cookies, you can write:
Cookie cookie = new Cookie(“time”,”20080808″);
cookie.setPath(“/session/”);
response.addCookie(cookie);
When set to “/” allows all paths to use cookies. The path attribute needs to end with the symbol “/”. Two cookies with the same name but the same domain are also two different cookies.
Note: The page can only get the cookie of the Path to which it belongs. For example, /session/test/a.jsp can not get to the path /session/abc/ Cookie. Must pay attention when using.
Cookie security attributes
The HTTP protocol is not only stateless, but also insecure. Data using the HTTP protocol is transmitted directly over the network without any encryption and is intercepted. Using the HTTP protocol to transfer very confidential content is a hidden danger. If you do not want cookies to be transmitted in non-secure protocols such as HTTP, you can set the cookie’s secure property to true. Browsers only transmit such cookies in secure protocols such as HTTPS and SSL. The following code sets the secure property to true:
Cookie cookie = new Cookie(“time”, “20080808”);
cookie.setSecure(true);
response.addCookie(cookie);
Tip: The secure attribute does not encrypt the contents of the cookie, and therefore can not guarantee absolute security. If you need high security, Cookie content in the program need to be encrypted, decrypted, to prevent leakage.
JavaScript operation Cookie
Cookies are saved on the browser side, so browsers have the prerequisites for operating cookies. Browsers can manipulate cookies using scripting programs such as JavaScript or VBScript. Here to JavaScript as an example to introduce commonly used cookie operation. For example, the following code will output all the cookies on this page.
<script>document.write(document.cookie);</script>
Because JavaScript can read and write cookies arbitrarily, some decent people want to use JavaScript programs to spy on users’ cookies on other websites. However, this is futile. The W3C has long realized that JavaScript addresses the security risks of reading and writing cookies. The W3C standard browsers prevent JavaScript from reading or writing any cookies that are not owned by the site. In other words, A website JavaScript program to read and write Web site B cookie will not have any result.
Case: permanent login
If the user is in his home computer on the Internet, you can log in to remember his login information, do not need to log in again next visit, direct access to. The implementation method is to log information such as account number, password, etc. stored in the Cookie, and control the validity of the cookie, the next visit to verify Cookie login information can be.
There are several options for saving your login information. The most direct is to keep the user name and password to the cookie, the next visit to check Cookie username and password, compared with the database. This is a more dangerous option and generally does not save important information such as passwords in cookies .
Another solution is to encrypt the password to save it to the cookie, the next time it is decrypted and compared with the database . This program is slightly safer. If you do not want to save the password, you can also save the login timestamp to the cookie and the database, only to verify the user name and login timestamp on it.
These programs to verify the account must check the database.
This example will use another program, check the database only when you log in, later access to verify login information no longer query the database. The realization method is to encrypt the account according to certain rules, together with the account number saved to the cookie. The next visit only need to determine whether the account encryption rules can be correct . This example saves the account to a cookie named account, encrypts the account with the key using the MD1 algorithm, and saves it to a cookie named ssid. Verify that the account and the key in the cookie after encryption are equal to the ssid in the cookie.