Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to thoroughly understand Cookie and Session

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/01 Report--

In this issue, the editor will bring you about how to thoroughly understand Cookie and Session. The article is rich in content and analyzes and narrates it from a professional point of view. I hope you can get something after reading this article.

When I was an interviewer, I asked a lot of friends this question: what's the difference between Cookie and Session? Most interviewers should be able to say one or two words, such as: what is Cookie? What is Session? The difference between the two.

However, if we go further into it, some friends will gradually fail to understand it, and when it comes to the principle, very few friends will have accurate answers. Today, let's have an in-depth talk about Cookie and Session.

The first floor

What are Cookie and Session?

What is Cookie?

HTTP Cookie (also known as Web Cookie or browser Cookie) is a small piece of data that the server sends to the user's browser and saves locally, and it is carried and sent to the server the next time the browser makes another request to the same server. Typically, it is used to tell the server whether two requests come from the same browser, such as keeping the user's login status. Cookie makes it possible to record stable state information based on stateless HTTP protocol.

Cookie is mainly used in the following three aspects:

Session state management (such as user login status, shopping cart, game scores, or other information that needs to be recorded)

Personalized settings (such as user-defined settings, themes, etc.)

Browser behavior tracking (such as tracking and analyzing user behavior, etc.)

What is Session?

Session represents the process of a session between the server and the client. The Session object stores the properties and configuration information required for a specific user session. In this way, when the user jumps between the Web pages of the application, the variables stored in the Session object will not be lost, but will persist throughout the user session. The session ends when the client closes the session, or when the Session timeout expires.

Second floor

What's the difference between Cookie and Session?

The scope of action is different, Cookie is saved on the client side (browser) and Session is saved on the server side.

Different access methods, Cookie can only save ASCII,Session can store any data type, in general, we can keep some common variable information in Session, such as UserId and so on.

If the validity period is different, Cookie can be set to remain for a long time, such as the default login feature we often use. Session generally has a short expiration time, and the client closes or Session times out.

Privacy policy is different, Cookie is stored in the client, it is easy to be illegally obtained. In the early days, some people stored users' login name and password in Cookie, which led to information theft; Session is stored in the server, and its security is better than Cookie.

The storage size is different, and the data saved by a single Cookie cannot exceed 4K. The data that can be stored in the session is much higher than that in Cookie.

Most of the students can answer the contents of the first two floors accurately.

The third floor

Why do you need Cookie and Session, and what is the connection between them?

When it comes to why you need Cookie, you need to start with the browser. We all know that the browser is stateless (HTTP protocol is stateless), which means that the browser does not know whether Zhang San or Li Si is dealing with the server. At this time, we need a mechanism to tell the server whether the user is logged in and which user is performing the operation, then the implementation of this mechanism requires the cooperation of Cookie and Session.

So how do Cookie and Session work together? I drew a picture that you can understand first.

When the user requests the server for the first time, the server creates a corresponding Session based on the relevant information submitted by the user. When the request is returned, the unique identification information of this Session, SessionID, is returned to the browser. When the browser receives the SessionID information returned by the server, the browser will store this information in Cookie, and the Cookie records which domain name the SessionID belongs to.

When the user visits the server for the second time, the request will automatically determine whether the Cookie information exists under this domain name. If so, the server will automatically send the Cookie information to the server, and the server will obtain the SessionID from the Cookie, and then find the corresponding Session information according to the SessionID. If it is not found, it means that the user has not logged in or the login is invalid. If the Session is found to prove that the user has logged in, you can perform the following actions.

According to the above process, SessionID is a bridge between Cookie and Session, and most systems also verify the login status of users according to this principle.

Most of the students can explain the contents of the third floor clearly.

The fourth floor

Since the server determines whether the user is logged in according to the information in Cookie, how to ensure the normal operation of the whole mechanism if Cookie is disabled in the browser.

In the first scheme, a parameter of SessionID is carried in each request, which can be submitted by Post, or xxx?SessionID=123456... can be concatenated after the requested address.

The second scheme, Token mechanism. Token mechanism is mostly used in the mode of interaction between App client and server, and can also be used for user state management on the Web side.

Token, which means "token", is a string generated by the server as an identity for the client to make the request. The Token mechanism is similar to the usage mechanism of Cookie and Session.

When the user logs in for the first time, the server generates a Token based on the submitted user information, and returns the Token to the client in response. Later, the client only needs to bring the Token to request data without logging in and verifying again.

The contents of the fourth floor can be explained clearly by some students.

The fifth floor

How to consider the distributed Session problem?

In order to support more traffic in Internet companies, the back-end often needs multiple servers to support front-end user requests, so if the user logs in on server A, the login failure will occur when the second request goes to service B.

Distributed Session generally has the following solutions:

In the Nginx ip_hash policy, the server uses a Nginx proxy, and each request is allocated according to the hash that accesses the IP, so that a background server is regularly accessed from the same IP, which avoids the phenomenon of creating a Session in server An and distributing it to server B for the second time.

Session replication, when the Session on any server changes (add, delete, modify), the node serializes all the contents of the Session and then broadcasts it to all other nodes.

Share Session, server stateless messages, use caching middleware to manage users' Session and other information, to ensure that the response results distributed to each server are consistent.

The third scheme is recommended.

The sixth floor

How to resolve cross-domain requests? What is the principle of Jsonp cross-domain?

When it comes to cross-domain requests, we must understand the same origin policy of the browser. The same origin policy / SOP (Same origin policy) is a convention introduced by Netscape in 1995. It is the core and basic security function of the browser. Without the same origin policy, the browser is vulnerable to attacks such as XSS, CSFR and so on. The so-called homology means that the three "protocol + domain name + port" are the same, even if two different domain names point to the same ip address, they are not of the same origin.

Common ways to resolve cross-domain requests are:

It is avoided by proxies, such as using Nginx to forward requests at the back end, avoiding cross-domain problems in the front end.

Cross-domain through Jsonp

Other cross-domain solutions

Focus on the cross-domain principle of Jsonp. The same origin policy of the browser prohibits cross-domain requests, but the

Tags are exceptions and are not subject to the same origin policy. Jsonp makes use of the cross-domain feature of tags to access cross-domain data.

The idea of JSONP is to agree on a callback function name with the server. After receiving the request, the server will return a Javascript. In this Javascript code, the agreed callback function is called and the data is passed as a parameter. When the Javascript code is received by the web page, the callback function is executed, and the data has been successfully transferred to the client.

The disadvantage of JSONP is that it only supports GET requests and does not support other types of HTTP requests such as POST requests.

The above is the editor for you to share how to thoroughly understand Cookie and Session, if you happen to have similar doubts, you might as well refer to the above analysis to understand. If you want to know more about it, you are welcome to follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report