HTTP session principle explanation and application

Source: Internet
Author: User
Tags keep alive

First explain what a session is. In computer terminology, a session is a process in which an end user communicates with an interactive system, such as entering an operating system from an input account password and exiting the operating system. More sessions are used on the network, and TCP's three-time handshake creates a session, and TCP closes the connection by closing the session. The language can be interpreted as: You call your girlfriend's phone number, your girlfriend answer, and then a "dear", until either side hung up the phone, the process is a session. You tease a puppy, it interacts with you, it is a conversation, it does not bird you, it does not form a conversation.

second, what is HTTP Session

The State of the Protocol is the ability of the next transmission to "remember" the transmission of this information, and HTTP is not to maintain the information transmitted by the connection for the next connection. From the traditional Web view: Stateless means that when the browser sends a request to the server, the server responds, but the same browser sends the request to the server, he will respond, but he did not know that you are just that browser, simply said that the server will not remember you, so is a stateless protocol. The essence is: HTTP1.0 is short-connected (here first ignores the HTTP1.1 keep alive bar), after the request response, the TCP connection is disconnected, the next connection is unrelated to the last one. To identify whether different requests are from the same client, reference the HTTP session mechanism, that is, the case that maintaining a connection between multiple HTTP connections between a user and a different request from the same user is called maintaining a session. Sessions are created through session management, information is stored, closed, and so on.

Third, HTTP the implementation mechanism of the session

cookies and sessions are a variety of teaching materials, and the online article describes two content related to the HTTP session. The more common explanation for this is that the cookie exists in the browser and the session is stored in the server. This explanation is the most shallow, very not rigorous, but can not be said to be wrong. Start with a cookie, a long time ago, in order to complete the HTTP session, those Internet designers thought of a way to store user information in the browser, each request to the server to send this information, so that the service side know the request sender is who, you know what information should be returned to the customer. But the problem soon appeared, Zhang San impersonating John Doe's name to send a request to the server, the server sent John Doe related information to Zhang San. For the sake of security, the internet Big Brother also thought of a way to identify the user's identity, is to store customer information on the server (session), all the user's identity is specified by the servers. Until now, the session has been successful in the mainstream of the HTTP session, should be said to be absolute control of the status.

How does session identification work? First, the client sends a request to the server, the server receives the request (there is no need for the session control of the situation), the initialization session, generate the corresponding session information, the core is the session ID, the session ID is sent to the client, the clients receive the session ID, store it, the next time the request is sent, Attached with this session ID is sent to the server side, the server as long as according to this session ID, will know who is. This session ID, like our ID number, has been with you for a lifetime. Core: How the server generates this session ID and how the client stores the session ID.

Iv. How to store a session ID ( SESSION ID )

The

         server stores session IDs in a number of ways, common to local storage, such as plain text, and text names as session IDs. For file systems, in the same directory, only one file is allowed for the same file name, so using the session ID as the file name is the only way to determine the session. In addition to local file storage, you can use database storage such as Memcache, Redis, or MySQL, which is stored using a third-party database. There is only one principle: the stored session ID must be unique.

After the client receives the session ID returned by the server (or service-side), does it use the file name as the server to store session information in the text as a session ID? It is possible for a client to communicate only with the same server, which is understood to be the same service-side handler. However, HTTP is due to the World Wide Web, the browser as the most common HTTP client, need to access a variety of Web sites, if the session ID as a file name, such a file with the session information, there will be a situation such as: N different sites, the server is using the same session generation algorithm, At the same time, it is likely that the same session ID will be generated, and the client cannot uniquely determine which server the session ID is communicating with, that is, the client "does not recognize" the server, and the session cannot be completed. How do I determine the service-side identity? That is, using domains, different domains have separate sessions. The client creates session files (client storage) with domain-related information as file identifiers to store session information, where the domain session ID is combined to uniquely identify the server and determine the conversation. Then, information such as the session ID is stored in a file with the "domain" information as the filename. Each time a service is requested for a domain, the stored session ID is attached to the request and sent to the server. Browser is the most common HTTP client, the browser stores the session information, is the use of cookie file, which holds the cookie information, and the server returns the session ID is also stored inside. The session ID is stored in the cookie file as a general case, and the cookie information is sent to the server as an HTTP hair, that is, the session ID is included with the request header in this case. However, HTTP requests, in addition to header information, can also have a content body that must have a URL. Then, the session ID can also be stored in the content body or URL, such as in the case of disabling browser cookies, can also be implemented with the server-side session, or dependent on the content body, or rely on the URL, the common is the URL with the session ID, which is common in programming languages such as PHP (historically common , but will involve security or efficiency issues, not detailed here).

Roughly, the session ID that is understood to be returned to the client by the server is stored in a cookie file. Cookie files are managed by the browser, of course, in the self-implemented client, you can programmatically implement cookie file management, that is, client session management. For example: iOS developers can store the headers returned by HTTP in a sandbox for management. When you develop a client in PHP, you can write the header to a file, or to a third-party service, or to a networked store, and so on.

v. Session Management ( SESSION )

Session Management includes: session creation, session recognition, session information operations, session life cycle, session shutdown.

Note: The server-side sessions in this section are considered to be open, without any special circumstances.

1. Session Creation

The client initiates an HTTP request without a session ID, which the server believes has not yet generated a session, that is, creates a session, generates a session ID and stores the relevant session information in the servers, and notifies the client that the session has been turned on. In general, the session ID is included in the cookie entry in the HTTP header returned to the client, in the form: Session token: Session ID. The client sets the local cookie value and stores it based on the returned information header.

2. Session Recognition

The session ID is the unique identifier for the session, and a session ID corresponds to only one session, just as the ID number corresponds to only one person. In HTTP, the server is passively accepting the request, and session recognition is also passive (triggered). The server does not need to know who is sending the request, just need to know the caller sent over the session ID, the client passed the session ID and the server store session ID to match. The session ID cannot be found and the session is not considered to exist.

Example: The server has a session ID of "21412545JLADFJLJLJQWR", the value of the map is "name: Zhang San, gender: male." The client recognizes this session as long as the session ID in the request is "21412545JLADFJLJLJQWR", which can be thought of as a Zhang San and a man. If the client requests a session ID of "QWESADFASDFADSFASDF", even if the client comes with the message "First name: Zhang San, gender: Male", the server does not think that this person exists and does not form a session. Even if the John Doe steals the Zhang San session ID, the server will recognize the session.

Can be simply understood as: Session only based on sessions ID set up a conversation, is not responsible for security checks, only responsible for the server and the client can "call."

3. Session Information Operations

Server: Session ID mapping information, ID unchanged, mapped content variable

Client: The session ID mapping information, the ID is not changed, the content of the map is mutable (that is, the content that exists in Cookiek is mutable).

The session information of the server and the client must be the same only if the session ID is the same, and the other session information (that is, the session ID mapping information) is not directly related.

4. Session life Cycle

A session is the life cycle of a session from start to finish. Set a time, this time without communication to clear the session information, we will call this time the session timeout period.

In practice, we call the session timeout period the life cycle of the session, which is actually two concepts.

5. Session closed

Session closed, there are 2 ways. One is the user actively cleans up the session information, and the other is the session timeout. Session timeout is not a daemon (or automatic task) periodic check processing, but rather access to the session information, based on the session information in the "Last update Time" to the present difference, the session period comparison, out-of-cycle, clear the conversation information, that is, the session closed.

Classic example: During a session, the network is suddenly disconnected.

Six, session check and HTTP Power of Protocol

A brief description of the power of http:

From the definition point of view, the power of the HTTP method is that one and multiple requests for a resource should have the same side effects. Idempotent is a semantic category, just as the compiler can only help check for syntax errors, and the HTTP specification does not have the means to define it by means of syntax such as message format, which may be one of the reasons why it is less valued. But in fact, idempotent is a very important concept in the design of distributed system, and the distributed nature of HTTP also determines its important position in HTTP.

For example (excerpt online): Suppose there is a remote API that takes money from an account (which can be HTTP or not), we temporarily use the class function as: bool Withdraw (account_id, amount). Requests the server, decreases the amount amount of the account_id, returns true successfully, and returns False if the amount of the failure is unchanged.

If the server succeeds, and returns true, but the network is interrupted, the client does not receive the information, the client considers that the money is failed, requests again, and the server charges again. This involves a duplicate request for the same operation.

To solve this problem, we can design the withdraw as idempotent. The semantics of Create_ticket is to obtain a server-side generated unique processing number ticket_id, which will be used to identify subsequent operations. The difference between Idempotent_withdraw and withdraw is that a ticket_id is associated, a ticket_id represents an operation that is processed at most once, and each call returns the result of the first invocation. In this way, the Idempotent_withdraw is idempotent, and the client can safely call it multiple times.

From the above example, you can see that the role of create_cicket is to generate ID identifiers, and subsequent operations are based on this ID. The session ID is essentially idempotent, and after generating the ID, the subsequent operations all carry the ID parameter, that is, the corresponding relationship between the operation information and the ID is established. The above example is not secure, just to ensure that the operation is unique to the same person (one session process). Similarly, the session ID is only recognized as identity, not a security guarantee.

Simple session Check:

A simpler session check is the use of tokens, that is, in addition to the session ID in the request, at least a token is also carried. Server-side-to-token checksum. Tokens are generated by a server based on an algorithm, and token validation is also handled on the server, where the client simply stores the token, carries the token in the request, and the complexity of the token generation algorithm affects the security of the token checksum.

Example: Tokenfunc (param,value= ") The first parameter is the token generation parameter, and the second parameter is the token value.  When the second argument is NULL, genetic token returns string, and the second argument is not NULL, check token accuracy and return bool. Generally do not need to decrypt, as long as the hash encryption. The PHP code is as follows:

function token ($param, $value = ") {

if (!is_string ($param) {

$param = serialize ($param);

}

$token = MD5 ($param. ' Sault ');

if (!empty ($value)) {

if ($value = = $token) {

return true;

}else{

return false;

}

}else{

return $token;

}

}

Generate tokens: $token = token ($session _id);

Test token: $check = token ($session _id, $token);

Seven, the application of conversational principle

The browser opens the cookie by default, when the browser initiates an HTTP request, with the cookie information in the request header, as long as the server returns a cookie containing SessionID, the HTTP session is implemented on the server based on SessionID. This process is transparent to front-end developers (that is, front-end development may not care how the browser determines the session with the server).

In addition to instant messaging, real-time action online games, most apps use the HTTP protocol to communicate with the server, the main reason for using the HTTP protocol is that the mobile network environment is complex (easy to break), and the HTTP protocol penetration is strong. Native-developed iOS, Android and other apps, and server-side sessions, can not use cookies, only need to carry the session ID in the request, which is described above. Native app compared to embedded browser app: Native achieves higher performance, interactive effect is smooth, user experience is relatively good, but fast fall generation than embedded browser app. Mobile phone configuration More and more high, embedded browser to HTML5 support is also getting better, in the performance requirements are not very high scene, embedded Web performance has been satisfied, in the layout is changeable, or the element is changeable, can be quickly modified, without the need for users to upgrade the app, but also to get a better product experience. App embedded web most common scene is the e-commerce app, login, registration, import and other interactive effects more modules using the native program development, and commodity list, product display and so on modules can be embedded in the web, so as to meet the rapid product fall generation requirements, but also to meet the performance requirements of the operation.

Example: E-commerce App entry interface, login, registration is the use of native development, landing after the jump to the Product List page (that is, embedded web), and then place an order. The question is, how to make the landing after the jump to the web, or the status of the login (that is, the embedded web and the native program has a consistent session)? The embedded web is not going to get the data stored by the native program. The simplest and most straightforward way is to log in successfully, the server returns session ID and success information, when you jump to the Web, the HTTP request header that is sent includes a cookie, the session ID is stored in a cookie, and then you click the link in the Web and then send the HTTP request header to the service side. Will carry this cookie (session ID). Simple understanding: The terminal native program requests the service side, the service side returns the information according to the ordinary web, the terminal native program obtains the cookie information in the HTTP return header, saves, the next request, carries the cookie information. In the browser, the processing of the cookie is handled by the browser by default, while in the native app, the developer writes the program to handle it.

HTTP session principle explanation and application

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.