By the end of this article you will be rewarded

  • What is a Cookie and what does it do
  • How are cookies stored in Android
  • The specific meaning of the field in Cookie and how to parse it

What is a Cookie

  1. When we make a network request, we usually use Http protocol, for example, enter Http :www.baidu.com in the browser to request baidu website.

  2. HTTP/1.1 is a stateless protocol, meaning that the server does not know the status of the client. If interface A is requested to log in and then interface B is requested to obtain data, if some login parameters are not manually splicing when interface B is requested, the server does not know whether we are logged in at this time. Concatenating parameters in each interface is a bit cumbersome, and that’s where cookies come in.

  3. Cookies can be used to cache some data on the client side, or to persist the data. Under certain conditions, this data is brought along when the network requests it so that the link between the server and the client has a “state”. For example, the server can record the login status (token) in the cookie of the client upon successful login. The client automatically sends the cookie to the server if the conditions are met in the next request to the server, so that the server knows the login status of the client.

Http and WebView cookies

  1. In an Http request from a WebView, the server can set cookies in the Header of the Response returned by the request. When the WebView receives these cookies, it will cache or store them according to the meaning, such as
HTTP/1.0 200 OK Content-Type: text/ HTML set-cookie: theme=light set-cookie: sessionToken=abc123; Expires=Wed, 09 Jun 2021 10:18:14 GMTCopy the code
  1. When making a web request, the WebView will help us with the stored cookie in the request if it meets the criteria, such as
GET /spec. HTML HTTP/1.1 Host: www.example.org Cookie: theme=light; sessionToken=abc123Copy the code
  1. Where does the WebView store these cookies? If cookies are not out of date and need persistent storage, WebView will typically store them in a database

Cookie in the Android

As mentioned above, cookies are stored in WebView. Are cookies used in non-WebView scenarios? The answer is yes, for example: if we log in to the Android App and open a Web in the App, how will the Web know if we are logged in? We can use cookies to write the corresponding login information into cookies when we call Http to request login successfully, and the Web will read these information to know whether we have logged in

Use CookieManager to store and read cookies

WebKit in Android provides us with CookieManager, which is a singleton that we can use to read and store cookies, for example

 /**
     * Sets a cookie for the given URL. Any existing cookie with the same host,
     * path and name will be replaced with the new cookie. The cookie being set
     * will be ignored if it is expired.
     *
     * @param url the URL for which the cookie is to be set
     * @param value the cookie as a string, using the format of the 'Set-Cookie'
     *              HTTP response header
     */
 val value = "gw_id=6404; Path=/; Max-Age=86400; HttpOnly"
 CookieManager.getInstance().setCookie(url, value)
 CookieManager.getInstance().getCookie(url)
Copy the code

Domain name Sharing Cookie

In some scenarios, if we need different domains to share cookies, we need to do something extra. Why?

  1. A Cookie contains several attributes, including the host, name, and path to which it takes effect. For example, in the example above, URL is the domain name, gw_id is name, and/is path.
  2. As we mentioned earlier, the Web only brings cookies to the server on a request under certain conditions: the domain name of the cookie is equal to the domain name of the current request.
  3. However, there are some special scenarios. For example, the company has N domain names, and the user logs in to the website of domain NAME A. If he visits the website under domain name B, does he need to log in again? This is where domain name sharing is needed
  4. In Android domain name sharing can use the CookieManager above, at A specific time to read the Cookie of A domain name, and then set to B domain name, so that B domain name can access the Cookie of A domain name

Parse cookies in the database

  1. As mentioned earlier, cookies are usually stored in a database. What about in Android? This database is located in the Cookies file under data/data/ package name/AAP_webview. This may vary with Android systems. For example, Huawei is located under data/data/ package name/AAP_webview /default

  1. Since it is a database file, naturally can be resolved through the database, we can set some cookies through the above CookieManager setCookie method (note: There is a cache in the database, Cookies will not be written immediately after using CookieManager to access. If you want to write Cookies immediately, you can call CookieManager flush() method), and then take out the Cookies file. And change the name to Cookies. Db, and then use database software (the author used DB Browser for Sqlite) to read (note: different versions of webView may generate different table keywords).

  1. The first figure above shows the field types and default values, and the second figure shows an example. What do these fields mean?
key meaning
creation_utc Utc time when cookies are generated
host_key Domain for which the cookie is currently valid (set the parent domain and apply to the child domain)
name Key3value To save Value to save (unencrypted
path Path, such as /docs/Web/, if set, cookie only applies to the current path
expires_utc Cookie expiration time (unit: ms
is_secure If true, change cookies are transmitted only if HTTPS is used, not HTTP
is_httponly If true, the cookie should not be manipulated by the client (cookies with HttpOnly tags cannot be accessed through JavaScript’s Document.cookie API) and should only be sent to the server for processing
last_access_utc Utc time the Cookie was last accessed
has_expires Whether the Cookie is valid
is_persistent If expiRES_UTC is not 0, the value is 1. (There are two storage types of cookies: session and persistence. When the Expires attribute defaults, it is a session Cookie that is only stored in client memory and Expires when the user closes the browser.)
priority Cookies also have a storage upper limit. When the upper limit is exceeded, cookies need to be deleted. In this case, specific deletion policies will be used to delete cookies with different priorities
encrypted_value Value Encrypted value
samesite None (0) browser continues to send cookies, case insensitive, on same-site requests and cross-site requests. Strict (2) The browser will only send cookies for the same site request (that is, the current web page URL is exactly the same as the target URL of the request). Cookies marked with the Strict attribute are not included if the request comes from a DIFFERENT URL than the ONE for the current location. Lax (1) As the default option in newer browsers, same-site cookies will be reserved for cross-site sub-requests, such as image loads or calls to frames, but will only be sent when the user navigates to a URL from an external site.
firstpartyonly First-party and third-party are two types of HTTP requests. First-party means that the URL of the HTTP Request is the same as that in the address bar of the browser. Otherwise it’s third-party.
  1. Firstpartyonly does not appear in the previous screenshot. Why? As mentioned earlier, the key of the table generated by different versions of WebView is different. In some versions, FirstPartyOnly will replace Samesite. Similarly, persistent instead of is_persistent

  2. So what does Samesite mean? Its function is actually very simple, suppose we have A scenario, under the webpage of domain NAME A, need to request domain name B, then how to bring the Cookie? Would it be unsafe? This is where Samesite comes into play

  3. It also mentions utc time, which looks like this in the screenshot: 13260634474538121. What standard time is this? It starts on January 1, 1601, and is measured in subtleties. It differs 11644473600 miles from the usual date of January 1, 1970

  4. Is_persistent and has_expires indicate whether a cookie has an expiration date. When the cookie reaches the expires_UTC expiration time, the cookie will expire and we will no longer be able to retrieve the cookie from we. But in a special case, if expires_UTC is 0, IS_persistent is 0, and has_expires is 0, we can still get the Cookie from the Web or CookieManager