Token、session & cookie

1 Introduction

All week, IM is a typical fast stream switching system, the mainstream of today's IM systems (especially mobile terminal IM) exchange data stream is connected short Http + TCP or UDP connection length is achieved. Http connection is mainly used for short persistence reads various information from the server: such as user information, chat histories, buddy lists, etc., it is a long connection to transmit and receive real-time chat messages or instructions.

IM system as an indispensable technology, the importance of short Http even irreplaceable, but as a traditional Internet Http exchange of technical information, some typical concepts such as: Cookie, Session, Token, IM for novice programmers do not easy to understand. Given the importance of short Http connected IM system, how to correctly understand Cookie, Session, Token such things, determines your ability to find technical solutions best practices. The following will explain these three principles, based on the correct use and application scenarios.

2. What is a Cookie?

Cookie technology produced from the rapid development of the HTTP protocol on the Internet. With the horse galloping age of the Internet, bandwidth limit does not exist, people need more sophisticated Internet interaction, it must remain active (abbreviation: keep-alive) with the server. Then, in the early development of the browser, in order to meet the needs of users of various technical means to launch a Web browser to maintain state, including the Cookie technology. Cookie is a text file stored in the browser directory in the computer when the browser is running, play a role in the RAM memory (this is called Cookies Session Cookies), once the user exits from the site or server, can be stored in a Cookie on the user's local hard disk (referred to as such Cookies Persistent Cookies).

Cookie Origin: In 1993, Netscape to allow users to access a website to further enhance access speed, but also to achieve further personal network, invented the Cookie widely used today.

Timeliness Cookie: Cookie At present, some are temporary, while others are ongoing. Cookie save only a temporary period of time specified in the browser, once more than the prescribed time, the Cookie system will be cleared.

Cookie Limitations: Cookie must be set before the contents of the output HTML files; different browsers (Netscape Navigator, Internet Explorer) to deal with inconsistent Cookie, the use must be considered; the client user if the settings prohibit Cookie, the Cookie can not be established . And the client side, a number of Cookie browser can create up to 300, and each can not exceed 4KB, the total number of Cookie settings for each Web site can not be more than 20.

Implementation process:

A: First, the client sends a http request to the server;

B: the server receiving the client request, transmits a http response to the client, the response header, which contains Set-Cookie header;

C: A client initiates a second request (Note: If we need to take the server Cookie, we need to get this Cookie at step B above and as a request to initiate a second request with the head), is provided to the server information can be used to uniquely identify the client's identity. At this time, the server can also determine whether to enable the client does not accept cookies. Although the user may suddenly disable the use of cookies in process and applications that interact in it, but this situation is unlikely to happen basically, it can not be taken into account, which also proved to be right in practice.

3、Cookie 和 Session

As we all know, HTTP is a stateless protocol, so every time the client makes a request, the next request can not know the status of the data contained on the first request, how can a user state data associating it?

For example, in a Taobao page, you make a landing operation. When you jump to the product page, how the server know that you are already landed status?

4, on the Session

Cookie though very convenient, but using the Cookie has a big downside, all the data in the Cookie can be modified on the client, the data is very easy to be falsified, some important data can not be stored in the Cookie, and Cookie and if in too many data fields can affect the transmission efficiency. To solve these problems, it creates the Session, Session data is retained on the server side.

In short: Session is for the server for the client is not a Session said. Session server adds the client is connected to flag when establishing a connection and the client will eventually be converted into a temporary Cookie sent to the client to the server software (Apache, Tomcat, JBoss), when the client requests the server first checks to see if carry this Session (temporary Cookie), if not it will add Session, if you do come up with the Session related operations.

Session of the operation carried out by a session_id. session_id is usually stored in the client's Cookie, such as in express in (say is Nodejs), default is connect.sid this field, when a request comes in, the server checks Cookie saved session_id through the session_id and server-side Session associated data, save and modify data.

This means is that when you browse a Web page, the server generates a random string of 1024 bits long, then there is your Cookie in connect.sid field. The next time you visit, Cookie will be with this string, then the browser will know that you are so and so last visited, and then remove the data from the last record in your body from the storage server. Because the string is randomly generated, and the median enough, so do not worry that someone can fake. The probability of a successful forgery probability of being suddenly broke into and killed the neighbor's dog is better than sitting at home when the programming is still low.

Session can be stored in:

  • RAM;
  • Cookie itself;
  • redis memcached or other cache;
  • Database.

Online, the caching scheme is more common, save the database, query efficiency is too low compared to the first three are not recommended; Cookie Session security issues, will be mentioned below.

The traditional authentication methods to be encrypted from the earliest to the Session and Cookie to the Session Cookie, then we look Token authentication.

5. What is the Token?

5.1 Token origin

Such as Ember, Angular, Web front-end framework like Backbone library is with more sophisticated Web applications and growing. For this reason, the formation of the server is also being freed from the traditional tasks and instead become more like API. Such that the concept of decoupling API traditional front and rear ends. Developers can from the front-end, back-end stand-alone development, greater convenience on the test. This approach also enables a mobile web applications and back-end applications can use the same.

When using one API, one of the challenges is the authentication (authentication). In traditional web applications, the server returns a successful response (response) depends on two things. First, he saved session information (Session) by means of a storage mechanism. Each session has its own unique information (ID), is often a long, randomized string that is used to retrieve information allows future requests (Request). Secondly, in the response header (Header) which causes the client information saved a Cookie. In each sub-server automatically request the inside with a session ID, which allows the server to identify the user in the Session Information Retrieval. This is the traditional method for web applications no escape HTTP connection (This is how traditional web applications get around the fact that HTTP is stateless).

API should be designed to be stateless (Stateless). This means not logged in, log out method, nor sessions, API designers also can not rely Cookie, because we can not guarantee that these request is issued by the browser. Naturally, we need a new mechanism. Token kind of thing came into being.

What is 5.2 Token

token is the user identity authentication, we usually call it: token. The simplest token consisting of: uid (user's unique identity), time (timestamp of the current time), sign (Signature by several former salt + hash algorithm to compress into a certain length of hexadecimal characters token string, a malicious third party can be prevented splicing request token server). The same argument can also be put token, avoid multiple search library.

We can imagine a safe Token passport. You are in a secure front desk to verify your identity (through your user name and password), if you successfully verified yourself, you can achieve this. When you walk into the building (trying to get resources from calling API), you will be asked to verify your passport, rather than re-verified at the front desk.

5.3 Token application scenarios

Token use process:

A: When a user first logs successfully (registration is also an applicable scenario), the server will generate a token value, this value will be saved in the server token value (stored in the database), then the token value is returned to the client;

B: After the client get token value stored locally. (SP storage is that we can support relatively easy to understand and storage operations);

C: When the client sends a request to the network (generally not login request) again, it will be included with this token value to the parameter sent to the server;

D: After the server receives the client's request, will remove the token value and token value stored in a local (database) do comparison.

Token authentication logic:

A comparison: if two token values ​​are the same, indicating that the user is logged over the current user is logged in!!

Contrast II: If there is no token value, then there is no successful login;

Comparison three: If the token value is different: the original description login information has expired, allowing users to log in again.

5.4 Token of security

We can save the certified Token recorded on the server, to add an additional layer of security, and then verify the record at every step verification Token of time (for example, every time a client requests API to check the legality of Token). This will prevent third-party disguise a Token, it will also enables the server to fail a Token.

6, Cookie and Session difference between Summary:

  • cookie data is stored on the customer's browser, session data on the server;
  • cookie is not very safe, people can analyze stored in a local cookie and cookie deception, should take into account the safe use of session;
  • session will be saved on the server for a certain time. When accessing the increase will compare the performance of your server footprint, taking into account mitigating server performance, you should use the cookie;
  • Single cookie saved data can not exceed 4K, many browsers are limited to a maximum of 20 sites saved cookie.

So My advice:

  • The login information and other important information is stored for the session;
  • Additional Information If you want to keep, you can put a cookie.

7, Token and the difference between Summary Session

Session token and not contradictory, as the authentication token security is better than Session, because each request signature also prevents eavesdropping and replay attacks, and Session must rely on the link layer to protect the security of communications. As mentioned above, if you need to implement stateful session, you can still increase the session to save some of the state on the server side

App usually dealing with a restful api with the server. Rest is stateless, that is not like the app browser as a cookie to store Session, hence the Session token to mark themselves enough, session / state by the logic api server processing. If you are not stateless backend of rest api, then you may need to save in the app in Session. Webkit can be embedded in the app, with a hidden browser to manage the cookie Session.

HTTP Session is a storage mechanism, mechanism for persistent object stateless HTTP provided. The so-called Session of the certification simply storing information to the User Session, because of the unpredictability of the SID, for the time being considered safe. This is a means of authentication. The Token, when it refers to OAuth Token or similar mechanism, then, is to provide authentication and authorization, certification is for the user, is authorized for App. Its purpose is to allow a right of access to information App a user. Token here it is unique. Can not be transferred to another on the App, you can not go to the other users. Turn around and say Session. Session provides only one simple authentication, that this SID, that is considered to have all the rights of this User. Is the need for strict confidentiality of this data should only be stored in the station square, you should not be shared with other sites or third-party App. So simple, if your user data and may require a third-party share, or allow third parties to call API interface, with a Token. If you always just your own website, their own App, what it does not matter.

When the Token is a token, such as your authorization (login) a program, he is a basis to determine whether you have licensed the software; cookie is written in a txt file on the client, which includes your login information and the like, so that you at login times a website, it will automatically call the cookie automatically log the user name; session and cookie almost, but Session is written in the file server, but also need to write cookie files on the client, but the file in your browser numbers . Session state on the server side, the client only Session id is stored; and Token status is stored in the client.

Go to article: https://www.wukong.com/answer/6694238137977143563/

Guess you like

Origin blog.csdn.net/weixin_34364071/article/details/90845916