The terms cookie and session are familiar to most of us, and are often used in HTTP interactions. But what exactly do they do? What are the differences and connections between the two?

What is a cookie

The definition of the cookie

According to the definition of Baidu Baike, cookies are “small text files”. They are the data (usually encrypted) stored on users’ local terminals by some websites for identifying users and Session tracking.

In plain English, it is:

  1. A cookie is a piece of data generated by the server (Web application) and stored on the client (user browser).
  2. This data is used for session tracing.
  3. The browser must carry this cookie in subsequent requests to the same website.

The purpose of the cookie

Because HTTP is a stateless protocol, each request is completely independent of the other. But in order for web applications to interact, multiple requests from the same user must be associated to generate meaningful behavior.

The most typical example is adding items to a shopping cart when shopping online. Since HTTP is a stateless protocol, how does the server know which users should add items to their shopping cart? That’s what cookies are for.

Cookie Usage Scenario 1: User login

After the user successfully logs in to the e-commerce website, the server will generate a login credential and return it to the user’s browser through the set-cookie field in the Response header to inform the user to save the Cookie information.

For example, the actual cookie is encrypted
Set-Cookie: uid=1
Copy the code

By default, the browser saves the cookie in a text file in a directory on the user’s PC. The cookie is carried in subsequent request headers sent to the website.

In this way, when the server receives the user’s request, it can also know which user the request comes from from the cookie carried by the request. In this way, the user login state is maintained.

Cookie Usage Scenario 2: Adding items to shopping cart

When the user adds commodity A to his shopping cart, the server can modify the cookie field to append the information of commodity A to the cookie, thus achieving the behavior of associating commodity A with the user.

The Set - cookies: uid = 1; prod=ACopy the code

When the user adds item B to the shopping cart, the server will append the information of item B to the cookie.

The Set - cookies: uid = 1; prod=A; prod=BCopy the code

When the user pays the bill, the server can get the information of all the commodities selected by the user from the cookie carried by the request.

What is a session

Session, as we call it, actually has two layers.

The first is its abstraction: the one-to-one continuous interaction between the client and the server is abstracted into a user session, or session. For example, a series of interactions between a user’s login and logout all belong to the same session.

The second is its practical concept: in order to maintain the user session, the server creates a session object to record various information of the user after login, such as the user name, user operations and so on.

Session is the unique information that identifies a user on the server, and the session information is returned to the user through cookies. In this way, user session tracking is realized on both the client and the server.

The difference and relation between cookie and session

  1. A cookie is stored on a client, such as the user’s computer, usually in a text. The session is stored on the server side, usually in a database or cache, but also in a file system.

  2. Cookie is a concept in THE HTTP protocol and is located in the Request header. The server can Set and modify the set-cookie field in the Response header to return the cookie to the client. Session is a server level concept, different programming languages may have different implementation methods, its purpose is to record and maintain the user’s state.

  3. Session persistence, as we often say, is actually to return the session state saved by the server to the client by virtue of the cookie feature, and continue the interaction through the cookie during the whole user session, so as to realize the session persistence at the abstract level.

Therefore, cookie itself is not necessarily related to session, it is just a common method used to realize session tracking.

Session implementation in Django

Django supports sessions through middleware. Session middleware is configured in settings.py by default when a project is created.

INSTALLED_APPS = [
    'django.contrib.sessions',
]

MIDDLEWARE = [
    'django.contrib.sessions.middleware.SessionMiddleware',]Copy the code

Django saves session information in a database by default. You can use manage.py Migrate to generate session tables. If the performance requirements are high, you can also save the session configuration to the cache.

mysql> desc django_session;
+--------------+-------------+------+-----+---------+-------+
| Field        | Type        | Null | Key | Default | Extra |
+--------------+-------------+------+-----+---------+-------+
| session_key  | varchar(40) | NO   | PRI | NULL    |       |
| session_data | longtext    | NO   |     | NULL    |       |
| expire_date  | datetime(6) | NO   | MUL | NULL    |       |
+--------------+-------------+------+-----+---------+-------+
3 rows in set (0.01 sec)
Copy the code

Django_session = djanGO_session;

Session_data Ciphertext generated after user information is encrypted and can be decrypted.

Session_key is a random string generated according to the session_data ciphertext, which has no actual meaning and is only used to insert into the cookie and return to the client. When the user initiates a request, the cookie carried in the request is matched with the Session_key in the DjanGO_session table to query whether there is a matched session_data.

Expire_date Records the expiration time of the session.

Practice is the sole criterion for testing truth

After the login request is initiated, the server carries the set-cookie field in the response header, which contains the csrftoken and the sessionid of the session.

(For the cSRFtoken mechanism in cookies, see CSRF Attacks and Django Defense)

Set-Cookie:  csrftoken=ATfjCEJZVaN9zTYnSHPzSRJhWfVfFlxntOYyu2f64j4mf9clzigVxsBIFN293uu3; expires=Sun, 28 Feb 2021 14:58:22 GMT; Max-Age=31449600; Path=/; SameSite=Lax
Set-Cookie:  sessionid=j0b9jsiiumwfjzmt9k3tw05aw7q5xk2n; expires=Sun, 15 Mar 2020 14:58:22 GMT; HttpOnly; Max-Age=1209600; Path=/; SameSite=Lax
Copy the code

In a Django database, you can see the corresponding record in the Django_session table as well

On the next request after login, you can see that the cookie in the request header already carries the sessionID returned by the server

At this point, through the session mechanism of the server and the COOKIE mechanism of THE HTTP protocol, the HTTP stateless protocol session persistence is realized, and users can have a pleasant page interaction.