Token and Cookie, Session login mechanism

Cookie

background

With the rise of the Web (the so-called interactive means that you can not only browse, but also log in, post comments, shop and other user operations), simply browsing the web can no longer meet people's requirements. For example, with the rise of online shopping, users need to be recorded For the shopping cart record, there needs to be a mechanism to record the relationship of each connection, so that we know who the product added to the shopping cart belongs to, so Cookie was born.


mechanism

insert image description here


example

Take adding to the shopping cart as an example, after each browser request, the server will store the item id in the cookie and return it to the client, the client will save the cookie locally, and the next time it will pass the last saved cookie to the Just give it to the server, so that each cookie saves the user's product id, and the purchase record will not be lost
insert image description here


shortcoming

As there are more and more items in the shopping cart, the cookie size for each request is getting bigger and bigger, which is a big burden for each request. I just want to add an item to the shopping cart. Why should I add The historical commodity records are also returned to the server together? The shopping cart information has actually been recorded in the server, and the operation of the browser is superfluous. The improvement method is as follows


Cookie + Session

mechanism

Since the user's shopping cart information will be stored in the server, it is only necessary to save the information that can identify the user's identity in the cookie and know who initiated the operation of adding to the shopping cart. In this way, after each request, only the user's identity needs to be included in the cookie Information, the request body only needs to bring the product id that was added to the shopping cart this time, which greatly reduces the size of the cookie. We call this mechanism that can identify which request was initiated by which user a Session (session mechanism). The generated The string that can identify user identity information is called sessionId
insert image description here

  1. First, the user logs in, and the server will generate a session for the user and assign it a unique sessionId. This sessionId is bound to a certain user, that is to say, according to this sessionid (assumed to be abc), it can be queried which user it is. Then pass this sessionid to the browser through the cookie
  2. After that, the browser only needs to add sessionId=abc key-value pair in the cookie for each request to add a shopping cart. After the server finds the corresponding user according to the sessionId, it saves the passed commodity id in the server corresponding to the user. shopping cart

This method no longer needs to pass all the product ids of the shopping cart in the cookie, which greatly reduces the burden of requests. Note that the cookie is stored in the client, while the session is saved in the server, and the sessionId needs to be passed with the help of the cookie to make sense


Pain points

The above situation can work normally because we assume that the server works on a single machine, and if it is deployed in a cluster, there will be problems. Assuming that the login request hits machine A, machine A generates a session and adds the sessionId in the cookie and returns it to the browser, then the problem arises: if the request hits B or C when adding a shopping cart next time, since the session is on machine A Generated, at this time, B and C cannot find the session, then there will be an error that the shopping cart cannot be added, and you have to log in again
insert image description here


Pain solution

  1. Session replication: A generates a session and copies it to B, C, so that each machine has a session, no matter which machine the request to add a shopping cart hits, the session can be found, the disadvantage is that the session saves multiple copies, and the data is redundant Remain
  2. Session adhesion: This method allows each client request to be sent to a fixed machine. For example, after a browser login request is sent to machine A, all subsequent requests for adding a shopping cart are also sent to machine A. Nginx The sticky module can support this method, and supports sticking by ip or cookie. After each client request reaches Nginx, as long as its ip remains unchanged, the value calculated according to the ip hash will be sent to a fixed machine, and there will be no The problem that the session cannot be found, the disadvantage is that as long as a certain machine is down, the corresponding request cannot be processed
upstream tomcats {   ip_hash;   server 10.1.1.107:88;   server 10.1.1.132:80; }

insert image description here

  1. Session sharing: The mainstream solution is to save the session in redis, memcached and other middleware. When a request comes, each machine can go to these middleware to get the session. The disadvantage is that every request has to go to redis to get the session , which is one more time Internal connection consumes a little performance. In addition, in order to ensure the high availability of redis, it must be clustered
    insert image description here

Token:no session!

mechanism

First, the requester enters his user name and password, and then the server generates a token based on this. After the client gets the token, it will be saved locally, and then the token can be attached to the request header when requesting from the server.
insert image description here


principle

1. The token is only stored in the browser, but not in the server. In this case, I can make a token and pass it to the server.

Answer: The server will have a verification mechanism to verify whether the token is legal.

2. Why don't you find the userid based on the sessionId like the session, so how do you know which user it is?

A: The token itself carries userid information

insert image description here
token is mainly composed of three parts

header: specifies the signature algorithm

payload: non-sensitive data such as user id and expiration time can be specified

Signature: Signature, the server knows which signature algorithm it should use according to the header, and then uses the key to generate a signature for the head + payload according to the signature algorithm, and a token is generated.

When the server receives the token from the browser, it will first take out the header + payload in the token, generate a signature according to the key, and then compare it with the signature in the token. If it succeeds, it means that the signature is legal, that is, the token is legal. And you will find that our userId is stored in the payload, so you can get the userid directly in the payload after getting the token, avoiding the overhead of getting it from redis like a session. As long as the server guarantees that the key is not leaked, the generated token is safe, because if the token is forged, it cannot pass the signature verification link, so the token can be determined to be illegal.


Notice

Once the token is generated by the server, it is valid until it expires, and the token cannot be invalidated unless a blacklist is set up for the token on the server, and the blacklist is checked before verifying the token. If it is in the blacklist, the token will be invalid , but once this is done, it means that the blacklist must be saved in the server, which returns to the session mode, so it is not good to use the session directly. Therefore, the general practice is to remove the token locally when the client logs out to invalidate the token, and just regenerate the token for the next login. The token is generally placed in the Authorization custom header of the header, not in the cookie. This is mainly to solve the problem that cookies cannot be shared across domains


Compared with Cookies
1. Cookies cannot be shared across sites, so if you want to implement multi-application (multi-system) single sign-on (SSO), it will be very difficult to use cookies to do what you need (a more complicated trick is required) to achieve)
but if you use token to implement SSO will be very simple
insert image description here
, just add token to the authorize field in the header (or other custom) to complete the authentication of all cross-domain sites.

2. There is no such thing as a cookie in the native request of the mobile terminal, and the sessionid depends on the cookie, so the sessionid cannot be passed by the cookie. If the token is used, it does not exist because it is passed along with the authorize of the header. This problem, in other words token inherently supports mobile platforms and has good scalability

To sum up, token has the characteristics of simple storage and good scalability.


shortcoming

1. The token is too long

The token is the encoded style of the header and payload, so it is generally much longer than the sessionId, and it is likely to exceed the size limit of the cookie (the cookie generally has a size limit, such as 4kb). If the information you store in the token is longer, then The token itself will be longer. In this case, since you will bring the token every time you request, it will be a big burden on the request.

2. Not very safe

We say that the token exists in the browser, where does it exist in the browser? Since it is too long to be placed in the cookie and may cause the cookie to exceed the limit, it has to be placed in local storage, which will cause security risks, because local storage such as local storage can be directly read by JS, and from the above It is also mentioned that once the token is generated, it cannot be invalidated, and it must wait until it expires. In this way, if the server detects a security threat, the related token cannot be invalidated.

So token is more suitable for one-time command authentication, set a relatively short validity period

Whether it is a cookie or a token, it is actually not safe from the perspective of storage, and there is a risk of exposure. What we call security is more about the security in transmission, which can be transmitted using the HTTPS protocol. In this case, the request header can be Being encrypted ensures the security in transmission.


Summarize

There is no difference between session and token in essence. They are both authentication mechanisms for user identities, but the verification mechanisms they implement are different (one is stored in the server, which is verified by obtaining middleware such as redis, and the other is stored in the client. , through signature verification), it is more reasonable to use session in most scenarios, but it is more appropriate to use token in single sign-on and one-time command authentication, it is best to choose a reasonable model in different business scenarios , in order to achieve twice the result with half the effort.

Detailed jump

Guess you like

Origin blog.csdn.net/huan1213858/article/details/132057843