HTTP 3 ways to manage Web sessions

Source: Internet
Author: User
Tags key string session id ticket

HTTP is stateless, one request ends, the connection disconnects, and the next time the server receives the request, it does not know which user the request was sent from. Of course, it knows which client address is sent, but for our application, we are managed by the user, not by the client. So for our application, it needs to be state-managed so that the server can know exactly which user initiated the HTTP request and determine if he has permission to continue the request. This process is often said to be session management. It can also be easily understood as a period of time for a user to log off from the app. This article summarizes 3 common ways to implement Web application session management:

1) Management method based on server end session

2) How to manage Cookie-base

3) How to manage Token-base

These content can help deepen the understanding of the user login mechanism in the web, and also have reference value to the actual project development, welcome to read and correct.

1. Server-side session-based management

In earlier Web applications, the server session was typically used to manage user sessions. Get a quick look at the server session:

1) The server session is the first time a user accesses an application, the object that is created on behalf of the user, a session process that can be used to hold the data. The server assigns a unique SessionID to each session to ensure that each user has a different session object.

2) After the server has created the session, it will return the SessionID through the cookie to the user's browser, so that when the user sends the request to the server the second and later, it will pass the SessionID back to the server through the cookie, So that the server can find the session object corresponding to the user according to SessionID.

3) The session usually has an expiration time setting, such as 2 hours. When the expiration time expires, the server destroys the previous session and creates a new session to return to the user. However, as long as the user in the expiration time, there is a new request to the server, usually the server will be his corresponding session of the expiration time according to the current request time extension 2 hours.

4) The session does not have the function of conversational management at the beginning. It can be used to manage the session only after the user has successfully logged in and the credentials are placed inside the Sesssion object for the user to log in successfully. The logic of the management session is also very simple, as long as the user's session object, see if there is no login successful credentials, you can determine whether the user has logged in. When the user exits voluntarily, it will clear the login credentials in its session object. Therefore, before the user login or after exiting or the session object is invalid, must not get the required login credentials.

The above process can be described as simple as a flowchart:

The mainstream web development platform (java,.net,php) natively supports this kind of session management and is very simple to develop, and I believe most back-end developers know and use it when they get started. It also has a big advantage is the security is good, because in the browser side and the server side to maintain the session state of the medium is always just a sessionid string, as long as the string is enough random, the attacker can not easily impersonate another person's sessionid to operate, unless by CSRF or HTTP hijacking way , it is possible to impersonate someone else, and even if the impersonation succeeds, it must be a valid login credentials to be included in the impersonated user session. But before you really decide to use it to manage your session, you have to consider the following questions for your application:

1) This way the session information is stored in the Web server, so the user at the same time online, these session information will occupy more memory;

2) When the application adopts cluster deployment, it will encounter the problem of how to do the session sharing among multiple Web servers. Because the session is created by a single server, the server that handles the user request is not necessarily the server that created the session, so that he cannot get the information such as the login credentials that were previously placed in the session;

3) Multiple applications to share the session, in addition to the above problems, but also encounter cross-domain issues, because different applications may be deployed differently, you need to do a cookie cross-domain processing in each application.

For issue 1 and Issue 2, the solution I have seen is to use Redis as an intermediary server to manage the session additions and deletions, one to alleviate the burden on the Web server, and to solve the problem of sharing the session with different Web servers. For Issue 3, because the server session relies on the cookie to pass SessionID, so in the actual project, as long as the implementation of the various projects within the SessionID cookie cross-domain access can be, this can be achieved, is more trouble, Both the front and back end may have to be processed.

This management approach is worth using, especially for small web applications, without considering the above three issues. But once the application is necessary for future expansion, it is prudent to deal with the previous three issues. If you really want to use this approach in your project, it is recommended that you use a single sign-on framework, such as CAS, to make your application more extensible.

2. How to manage cookie-based

Because the previous way will increase the burden of the server and the complexity of the architecture, so then someone came up directly to the user's login credentials directly to the client's scheme, when the user login successful, write the login credentials into the cookie, and set the validity period of the cookie, Subsequent requests directly verify the existence of the cookie that contains the login credentials and that the credentials are valid to determine the user's login status. The overall process of using it to implement session management is as follows:

1) The user initiates the logon request, the service side according to the incoming user password and so on identity information, verifies whether the user satisfies the sign-in condition, if satisfies, creates a login voucher according to the user information, this login voucher is simply an object, the simplest form can contain only the user ID, Voucher creation time and expiration time three values.

2) The service side of the previous step to create a good login credentials, the first to do a digital signature, and then use the symmetric encryption algorithm for encryption processing, signed, encrypted string, write to the cookie. The name of the cookie must be fixed (for example, ticket), because the cookie value is obtained by this name when it is later acquired. This step to add a digital signature is to prevent tampering with the information in the login credentials, because once the information is tampered with, the next step in signing verification will definitely fail. The purpose of encryption is to prevent the cookie being intercepted by others, it is not easy to read the user information.

3) After the user logs in to initiate subsequent requests, the server obtains the relevant cookie value based on the cookie name of the previous step storage login voucher. Then do the decryption process, then do the digital signature authentication, if these two steps fail, indicating that the login credentials are illegal, if the two steps succeed, then you can get the original deposited login credentials. Then use the expiration time of this voucher and the current time to make a comparison, determine whether the voucher expires, if it expires, the user will need to re-login, if not expired, allow the request to continue.

The greatest advantage of this way is to achieve the server-side stateless, completely remove the server-to-session management of the logic, the server only need to be responsible for creating and verifying the login cookie, do not need to maintain the user's state information. For the second problem of the first way, the user session information sharing problem, it can also be solved well: because if only the same application to do cluster deployment, because the code to verify the login credentials are the same, so regardless of which server processing user requests, always get the login credentials in the cookie to verify , if it is a different application, as long as each application contains the same login logic, then they can also easily achieve session sharing, but in this case, the login logic inside the digital signature and encryption decryption to use the key file or key string, need to be shared in different applications, in a word, Is that the algorithm needs to be completely consistent.

This way because the login credentials directly to the client, and the need to send a cookie, so its shortcomings are more obvious:

1) Cookies are limited in size and can not store too much data, so if there are too many messages stored in the login credentials, the string after the encryption signature will cause other problems, such as when other business scenarios require cookies, there may not be so much space available; To observe the actual size of the login cookie, such as too long, it is necessary to consider the digital signature algorithm is too strict, resulting in the string after the signature is too long, it is appropriate to adjust the signature logic; For example, if the first 4,096-bit RSA algorithm to do digital signature, you can consider switching to 1024, 2048-bit;

2) Each time the cookie is transmitted, the number of requests is increased and the performance of the access is affected;

3) There are also cross-domain issues, after all, it is necessary to use cookies.

Compared to the first way, the cookie-based scheme is obviously better, there are many web development platforms or frameworks used by default in this way to do session management, such as PHP inside the YII framework, which is the back end of our team is currently used, it is using this scheme, the above mentioned in the login logic, The framework has also been encapsulated, the actual use is also very simple; ASP. Forms Identity Authentication, is also this idea, here is a good article to its implementation details are said very clearly:

Http://www.cnblogs.com/fish-li/archive/2012/04/15/2450571.html

The previous two session management methods because all use the cookie, does not apply in the native app: the native app does not manage the cookie, after all, it is not the browser. Neither of these scenarios is suitable for login authentication of pure API services. To implement login authentication for API services, consider the third session management method described below.

3. How to manage token-based

This way, in terms of process and implementation, is not much different from the way cookie-based is, except that the ticket in the cookie is called token in this way, and after the token is returned to the client, the cookie-based. Subsequent requests must take the token in the form of a URL parameter or an HTTP header, so that the server receives the request directly from the HTTP header or URL to the token for verification:

In this way, tokens are not passed through cookies, but each time the request is made, the token is added to the HTTP header or behind the URL, so even in the native app it can be used to invoke the API interface that we publish through the Web. There are two things to do in the app:

1) to effectively store tokens, you have to ensure that each time you tune the interface can get the same token from the same location;

2) Each time the code of the interface must add tokens to the header or interface address.

Look trouble, in fact, no trouble, these two things, for the app, it is easy to do, as long as the interface calls the module a little encapsulation can be.

The same applies to Web applications, tokens can be stored in localstorage or sessionstorage, and then every AJAX request, the token is put out in the AJAX request header. However, if a non-interface request, such as directly by clicking on a link to request a page, it is not automatically bring tokens. So this approach is limited to Web applications that follow pure interfaces.

This approach also has cross-domain issues in Web applications, For example, if the application deployment in the A.COM,API service deployed in B.Com, from a.com inside the AJAX request to B.Com, by default will be reported cross-domain error, this problem can be used in cors (cross-domain resource sharing) to quickly resolve, the relevant details can read the previous Cors article detailed understanding.

The same problem with cookie-based in this way is the problem of ticket or token refresh. Some products inside, you certainly do not want the user login, operation for half an hour, the result ticket or token to the expiration time, and then the user has to go to re-login situation appears. This time you have to consider the ticket or token of the automatic refresh problem, in short, you can verify that ticket or token is valid, automatically extend the expiration time of ticket or token, and then return it to the client The client will replace the original ticket or token if it detects that the server has returned a new ticket or token.

4. Security issues

In Web applications, the security of Session management is always the most important security issue, which has a great impact on users.

First, from the session management credential, the first way of the session credential is just a sessions ID, so as long as the session ID is enough random, rather than a self-increasing number ID value, then other people can not easily impersonate someone else's session ID to operate The second way of the voucher (ticket) and the third Way of the voucher (token) is a digital signature on the server, and encryption processing string, so as long as the key is not disclosed, others can not easily get the effective information in this string and tamper with it. In short, these three types of session management credentials themselves are relatively safe.

Then from the client and the server HTTP process, when others intercepted the client request in the session credentials, can take this credential impersonate the original user, do some illegal operations, and servers are not recognized. This security problem can be solved simply by using HTTPS, although there may be a higher level of threat of HTTP hijacking, but we can do from the code to prevent, indeed this level.

The final security issue is csrf (cross-site request forgery). This has a lot to do with the code, in essence it is a loophole in the code, but in general the loopholes, as developers are not easy to find, only those who mindedly want to do something to find these loopholes, so the prevention of this problem is more dependent on the developer of this attack mode of understanding, Includes common forms of attack and coping methods. Regardless of the credential information itself how safe, others use CSRF, can get someone else's credentials, and then use it impersonating someone else for illegal operation, so there is time really much to understand the relevant information. For example, if we put the voucher directly behind the URL to pass, it is possible to become a CSRF vulnerability: When a malicious user in our app uploaded 1 images that reference his own site, when the normal user login after accessing the page contains this image, As this image is loaded, a GET request is sent to the malicious website, and when the request is received by the malicious website, the address of the page containing the image is visible from the Reffer header of the request, which contains the session credentials of the normal user. , so the malicious user gets the credentials of the normal user, and as long as this credential is not expired, he can impersonate the user for illegal operation.

5. Summary

In front of these three ways, each have their own merits and use of the scene, I think no one is the best, when the project, according to the future expansion of the project and the structure of the situation, in order to decide which is the most suitable. The purpose of this article is to introduce the principles of these methods in order to master the key factors of login verification in Web applications.

As a front-end developer, although the article introduces 3 ways of Session management, but the most closely related to the front-end is the third way, after all, the front-end development of SPA applications and hybrid applications are very popular, so master the way the certification process and use of the way, for the front end, Obviously, it's very helpful. Fortunately, the technology in this way has long been realized, and there are ready-made standards available, the standard is JWT (Json-web-token).

The JWT itself does not do any technical implementation, it simply defines how the token-based is managed, which specifies the standard content that should be included in the token and the process and method of token generation. There are already a number of technologies that have achieved this standard:

See more: https://jwt.io/#libraries-io

In order to have a more comprehensive understanding of the implementation of the third mode of conversation management, I chose to use Express and the above many JWT implementation in the Jsonwebtoken to study, the relevant content I will be in the next blog detailed introduction. This concludes the content of this article, thank you for reading, welcome to the next blog content.

HTTP 3 ways to manage Web sessions

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.