Introduction: Cookie is used in the project of the new company. In the major technology discussion groups, many developers have different opinions about Cookie, session and token, so it is time to review the foundation of HTTP and summarize the development experience. This paper focuses on the basic concepts and application scenarios of Cookie, Session and Token. And the administrative use of cookies. If the article is not good, please developers old drivers in the comment area.

1. What is Cookie?

Cookie technology originates from the rapid development of HTTP protocol on the Internet. With the galloping of the Internet era, bandwidth and other restrictions do not exist, people need more complex Internet interaction, they must keep active with the server (referred to as: live).

Therefore, in the early stage of browser development, in order to meet the needs of users, various means to maintain the state of Web browsing were introduced, including Cookie technology. A Cookie is a text file stored in the browser’s directory on the computer that takes effect in RAM while the browser is running (such Cookies are called Session Cookies). Once the user logs out of the site or server, Cookies can be stored on the user’s local hard disk (called Persistent Cookies).

The origin of the Cookie: Netscape employee Lou Montulli invented today’s widely used Cookie in 1993 to speed up access to websites and personalize the Web. (So, a small step in the evolution of human computing could be a modest laziness.)

Cookie timeliness: Currently some cookies are temporary and some are persistent. A temporary Cookie is stored on the browser for a specified period of time. Once the specified time is exceeded, the Cookie is cleared by the system.

Cookie restrictions: Cookies must be set before the content of the HTML file is output; Cookies are handled differently by different browsers (Netscape Navigator, Internet Explorer). If a client user disables cookies, cookies cannot be created. On the client, a browser can create a maximum of 300 cookies, and each Cookie cannot exceed 4KB. Each Web site can set a maximum of 20 cookies.

Execution process:

A: First, the client sends an HTTP request to the server.

B: After receiving the request from the client, the server sends an HTTP response to the client. This response header contains the set-cookie header.

C: The second request made by the client (note: if the server requires us to bring a Cookie, we need to retrieve the Cookie at step B and initiate a second request as the request header), provides information that the server can use to uniquely identify the client. At this point, the server can also determine whether cookies are enabled on the client. Although it is possible for a user to suddenly disable the use of cookies during interaction with an application, this is so unlikely that it can be ignored and has been proven correct in practice.

For ease of understanding, take a look at this process execution diagram to deepen the concept

So, where are the headers and cookies on the browser? Here’s a snapshot of one of them.

So, this is all about cookies on the browser, so in Android development, how do we manage and use cookies?

Okhttp is a classic network framework, and its API (this article is based on Okhttp3.0 and above, 3.0 API is different) is through the OkhttpClient CookieJar or interceptor to manage cookies. In theory, we can just set up the CookieJar or interceptor when we build the singleton OkhttpClient, and then the Okhttp framework will automatically manage the cookies for us by doing the specific operation (i.e. save the Cookie and fetch the Cookie).

The diagram below:

This is one of the simple and effective ways to manage cookies through the collection increment feature. But we’ll find out in the source code. First, the CookieJar is an interface.

The English notes are translated as follows:

The CookieJar interface provides powerful support and policies for HTTP cookies.

The implementation of this policy is responsible for choosing which cookies to accept and reject. A reasonable policy is to reject all cookies, even though this interferes with session-based own authentication schemes that require cookies.

For Cookie persistence, the implementation of this interface must also provide Cookie storage. A simple implementation stores cookies in memory; Complex systems can use a database that the file system uses to hold accepted cookies. The link here https://tools.ietf.org/html/rfc6265 cookie specified storage model updating and expired cookies strategy.

So, Okhttp’s source code tells us that we can store cookies in memory; Complex systems can use a database that the file system uses to hold accepted cookies. As a result, we can easily manage and use maps.

Continue to analyze the methods in the CookieJar interface and continue to use the source code

So there’s saveFromResponse(HttpUrl URL), loadForRequest(HttpUrl URL)

According to the jar method, the cookie can be saved from an HTTP response here.

Note that if the response, this method may be referred to as the second HTTP response, including a trace. For this insidious HTTP feature, the cookie here contains only the cookies it tracks. If we use this method, we will do a trace (i.e. store a cookie in the response header after the request is successful).

LoadForRequest: loads a cookie from this method into an HTTP request to the specified URL. The result this method returns from the network may be an empty collection. A simple implementation would return an accepted cookie that has not expired to match. Cookie in the request header when loading url.

In this way, we can complete Cookie nonpersistence with the above code. What? Nonpersistent? What is that?

Continue to give you popular science, in the above said, Cookie is time-sensitive, therefore, Cookie management is divided into persistent Cookie and non-persistent Cookie. Non-persistent cookies are stored in memory, which means that their life cycle is basically the same as that of app. After app is closed, cookies are lost. The persistent Cookie is stored on the local disk and will not be lost after the app is closed. So, if we want to use the Cookie persistence policy, the idea can refer to the above non-persistence policy, just need to change the storage mode:

A: The cookie is extracted from the response by the response interceptor and saved locally, and the cookie is extracted from the response by the request interceptor and added to the request

B: Customize the CookieJar, save the cookie locally in saveFromResponse() and fetch the cookie locally in loadForRequest().

Here, I’ll show you how to use Okhttp to force higher-value interceptors to persist cookies.

Save cookie interceptor -1

Save the cookie interceptor -2

The SaveCookiesInterceptor implementation first gets the value of the set-cookie field from Response and saves it locally through SharedPreferences.

Add cookies to the request header

AddCookiesInterceptor Request interceptor. This interceptor determines if there is a cookie in the request and adds it to the Header cookie.

With these interceptors in place, we can quickly implement Cookie persistence by simply putting the instance object into OkhttpClient. (PS: These interceptors are also super useful for synchronizing cookies)

Okhttp uses a cookie interceptor

Extension: how to synchronize the client’s cookies with H5’s cookies

The client synchronizes cookies with H5

www.jianshu.com/p/88084a66c…

2.Session

Session is for the server, there is no Session for the client. Session means that the server adds the client connection mark when establishing a connection with the client, and finally the server software (Apache, Tomcat, JBoss) converts it into a temporary Cookie and sends it to the client. When the client makes the first request, the server will check whether it carries the Session (temporary Cookie). If it does not, it will add the Session. If it does, it will take out the Session to do relevant operations.

Here’s a story from someone else’s family to reinforce the impression:

Before we talk about what a session is, let’s talk about why sessions exist and how they work.

We know that when we open a web page in a browser, we’re using HTTP protocol, and anyone who knows anything about computers knows that protocol, it’s stateless, so what is stateless? That is, this request and the last request are unrelated, unknown, unrelated. But the advantage of stateless is that it’s fast. The problem is that I want several requested pages to be related, for example: I logged in at www.a.com/login.php, and I want to login at www.a.com/index.php, but these are two different pages, that is, two different HTTP requests, and these two HTTP requests are stateless, that is, unrelated. So you can’t just read it in index.php and it’s already logged in in login.php!

So how? I can’t log in both of these two pages. Or use stupid method these 2 pages to query the database, if there is a login state, it is judged to be logged. Although this query database scheme is feasible, but every time to query the database is not a thing, will cause the pressure of the database. So it was this appeal that a new way for clients to store data emerged: cookies. Cookie is a small amount of information stored on the user’s own computer, it is a global domain name, as long as the storage path is set under the domain name www.a.com, so when the user visits with the browser, PHP can read the information in the cookie from any page of the domain name. So I have logged in at www.a.com/login.php, and I can also get the login information at www.a.com/index.php.

At the same time, you don’t have to repeatedly query the database. Although this scheme is very good, fast and convenient, but because cookies exist on the client side, and its storage size is limited, the most important thing is that users can be visible and can modify at will, which is very insecure. So how do you make it safe and easy to read information globally? Thus, at this time, a new storage session mechanism, session, was born.

Session is to resolve the association between two HTTP requests in one Session, so that they are connected, so that both pages can read the global Session information. Session information exists on the server side, so it solves the security problem.

3.Token

Token is the authentication method of user identity, we usually call it: token. The simplest tokens consist of: UID (the unique identity of the user), time(the timestamp of the current time), and sign(the signature, which is a hexadecimal string compressed by hashing the first few digits of the token plus salt to prevent malicious third parties from concatenating token requests to the server). You can also put unchanging parameters into tokens to avoid multiple library checks.

Application Scenarios:

A: After the user logs in successfully for the first time (registration is also an applicable scenario), the server will generate A token value, which will be saved on the server (in the database) and then returned to the client.

B: The client saves the token value locally after obtaining it. (SP storage is more supported and easy to understand the operation of the storage)

C: When the client sends another network request (usually not a login request), it will send the token value to the server with a parameter.

D: After receiving the request from the client, the server compares the token value with the token value stored in the local database

Comparison 1: If the two tokens have the same value, the login succeeds. The current user is logged in!

Comparison 2: If the token value is not displayed, the login fails.

Comparison 3: If the token value is different, the original login information is invalid and the user needs to log in again.

The difference between cookies and sessions:

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

2. Cookies are not very secure. Others can analyze cookies stored locally and cheat cookies.

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

4. The data saved by a single cookie cannot exceed 4K. Many browsers limit the maximum number of cookies saved by a site to 20.

5. Personal suggestions:

Store important information such as login information as session

Other information can be stored in cookies if needed

The difference between Token and Session:

Session and token are not contradictory, as authentication token is more secure than session, because each request has a signature and can prevent listening and replay attacks, while session must rely on the link layer to ensure communication security. As mentioned above, if you need to implement stateful sessions, you can still add sessions to store some state on the server side.

Apps typically interact with servers using restful apis. Rest is stateless, that is, app does not need to use cookies to save sessions like Browser, so it is enough to use session tokens to identify itself. Session /state is handled by the logic of API Server. If your back end is not Stateless’s REST API, you may need to save sessions in your app. You can embed WebKit in your app and use a hidden browser to manage cookie sessions.

Session is an HTTP storage mechanism designed to provide a persistence mechanism for stateless HTTP. Session authentication is simply a matter of storing User information in a Session, which is considered safe due to the unpredictability of siDs. This is a means of authentication. Tokens, if referred to as OAuth tokens or similar mechanisms, provide authentication and authorization, authentication for the user and authorization for the App.

The goal is to give an App access to a user’s information. The Token here is unique. It cannot be transferred to other apps, nor can it be transferred to other users. Turn to sessions. Sessions provide only a simple authentication that the SID has full rights to the User. This data should only be kept on the site and should not be shared with other websites or third-party apps. So simply put, if your user data may need to be shared with a third party, or allow the third party to call the API, use Token. If it’s always just your own website, your own App, it doesn’t matter what you use.

Token is a token, for example, when you authorize (log in) a program, it is a basis to judge whether you have authorized the software. Cookie is written in a TXT file on the client, which includes your login information and so on, so that the next time you log in a website, it will automatically call the cookie automatic login user name; The session is similar to a cookie, except that the session is a file written on the server side, and you need to write a cookie file on the client side, but the file contains your browser number. The Session status is stored on the server, and the client has only the Session ID. The Token state is stored on the client.


Scan the following TWO-DIMENSIONAL code, timely access to more Internet job interview, Java, Python, crawler, big data and other technologies, and massive data sharing: public account background reply “CSDN” can be free to receive CSDN and baidu Library download services; Public number background reply “information” : you can receive 5T quality learning materials, Java interview test points and Java summary, as well as dozens of Java, big data projects, the information is very complete, you want to find almost all

Recommended reading

☞ Programmers Spring Festival exclusive couplets, every sentence piercing the heart: read all laugh