As we all know, “HTTP is a stateless protocol”, that is, every time a client sends a request, a new request is received to the server, so the server does not know the history of the client’s request.

Simply put, users log in to a shopping mall and add goods to their shopping cart. Then they face the problem of distinguishing which people log in to the mall and which people put goods in their shopping cart. And websites need to manage those conversations.

Cookies, sessions, and tokens are used to manage sessions.

Cookie

A cookie is a very specific thing. It refers to a kind of data that can be stored permanently in the browser. It’s just a data storage function implemented by the browser.

  • Cookie stored on the client: A cookie is a small piece of data generated by the server and sent to the client. The client saves the cookie locally in the form of key-value and sends the cookie to the server when it requests the same website next time.
  • Cookies are non-cross-domain: each cookie is bound to a single domain name and cannot be obtained and used under other domain names. First-level domain names and second-level domain names are allowed to be shared (depending on domain).

Important parameters in the Cookie

parameter instructions The back-end
Domain Specifies the domain name to which the cookie belongs. Default is the current domain name cookie.setDomain("")
Max-Age Set the cookie expiration time, in seconds cookie.setMaxAge(10)
Path Specifies the path (route) under which the cookie takes effect. Default is ‘/’ cookie.setPath("")
HttpOnly If the httpOnly attribute is set for a cookie, the cookie information cannot be read through THE JS script, but the cookie can be manually modified through the Application, so it can only prevent XSS attacks to a certain extent, not absolute security cookie.setHttpOnly(true)
Secure Tells the browser that the Cookie can only be transmitted over Https, or forbidden over Http cookie.setSecure(true)

Problems with using cookies

  • Do not store sensitive data, such as user passwords, account balances, because stored in the client, easily tampered by the client, need to verify the validity before use
  • The amount of data that can be stored cannot exceed 4kb
  • A browser can store a maximum of 20 cookies for a website, and a browser is generally allowed to store only 300 cookies
  • The mobile terminal does not support cookies very well, and the session needs to be implemented based on cookies, so the mobile terminal is commonly used by token

Session

Session translates to “conversation”, which is like how we know who the other person is in our daily conversation. We usually make a note of the other person (Lao Wang or Ergou Zi).

The same is true for sessions. The server needs to know who is currently sending the request to it. To do this, the server assigns a different “id” to each client, and then each time the client sends a request to the server, it carries this id so that the server knows who the request is coming from. As for how the client saves this “identity”, there are many ways, for the browser client, everyone uses cookie by default.

  • Session is another mechanism for recording the state of the session between the server and client
  • “Session is implemented based on cookies.” The session is stored on the server side as a list of states, and it has a unique identifier sessionId, usually stored in cookies

Session Authentication Process


  • First, the client sends an HTTP request to the server.
  • After receiving the request, the server creates a corresponding session and sends an HTTP response to the client, which contains the set-cookie header. This header contains the sessionId.
  • After receiving the sessionId returned by the server, the browser stores the information in the cookie, and the cookie records the domain name of the sessionId.
  • When a user initiates a request for the second time, the browser automatically determines whether there is a Cookie in the domain name. If there is a Cookie in the request header, the browser automatically adds the Cookie to the request header and sends it to the server
  • Upon receiving the request, the server obtains the sessionId from the Cookie and searches for the corresponding Session information based on the sessionId. If the Session is not found, the user is not logged in or the login is invalid. If the Session is found, the user is logged in and can perform the following operations.

As can be seen from the above process, session authentication process is completed by “server session + client session ID”, so “session ID is a bridge connecting Cookie and session”.

Why do we have sessions when we have cookies

  • To use a session, you only need to store a session ID on the client side. In fact, a lot of data is stored on the server side. If all cookies are used, the client does not have so much space when there is a large amount of data (the data saved by a single cookie cannot exceed 4K, and the Session can store much more data than cookies).
  • Everything is stored on the client side and cannot be verified by the server, making forgery and impersonation easier. (It’s hard to forge a random ID, but easy to forge another username)
  • Cookies are just one way to implement a session. Although it is the most common, it is not the only method. (There are other ways to store cookies after they are disabled, such as placing them in urls, but placing them in urls has security and SEO implications)
  • Keep it all on the client, so if it gets hijacked, all the information gets out
  • As the amount of data on the client increases, the amount of data transmitted on the network also increases

Problems with using sessions

  • Sessions are stored on the server. When a large number of users are online at the same time, these sessions occupy a large amount of memory. You need to periodically clear expired sessions on the server
  • The mobile terminal does not support cookies very well, and the session needs to be implemented based on cookies, so the mobile terminal is commonly used by token
  • Poor scalability: For example, in order to support more traffic, Internet companies often need multiple servers at the back end to support front-end user requests. If A user logs in to server A, the login failure will occur if the second request is sent to service B. (Solution:Nginx IP_hash policy, Session replication, and shared Session)

Token

  • Token comes into being when the client frequently requests data from the server, and the server frequently queries and compares the user name and password in the database to determine whether the user name and password are correct or not.
  • “Simple token composition” : UID (the user’s unique identification), time(the timestamp of the current time), sign (the signature, the first few digits of the token are hashed into a hexadecimal string of certain length)

Token Authentication Process


  1. The client requests login using the username and password
  2. The server receives a request to verify the user name and password
  3. After successful authentication, the server issues a token and sends it to the client
  4. After receiving the token, the client stores it, such as in a cookie or localStorage
  5. Each time a client sends a request, it needs to carry a token issued by the server (putting the token into an HTTP Header).
  6. After receiving the request, the server verifies the token in the request. If the authentication succeeds, the server returns the corresponding data

Token-based user authentication is a stateless authentication mode on the server. The server does not need to store token data. The computation time of token parsing is used to exchange the storage space of session, thus reducing the pressure on the server and reducing the frequent query of the database

Refresh Token

The preceding tokens are all acesss tokens, which are used to access resource interfaces. There is also another kind of token — refresh token. “Refresh token is used to refresh the access token. “


Why refresh an Access Token when you have one?

Generally, the refresh Token has a long validity period. However, the validity period of the Access token is relatively short. When the refresh token expires, a new token can be obtained by using the refresh token. Imagine that if the access token is refreshed every time without refresh Token, All require the user to enter the login user name and password, will be very troublesome. With the Refresh token, this hassle can be reduced. The client directly uses the Refresh token to update the Access token without additional operations by the user. Of course, if the Refresh Token also fails, the user will have to log in again.

The refresh token and expiration time are stored in the server database and verified only when a new Acesss token is applied for. It does not affect the service interface response time and does not need to be kept in memory to handle a large number of requests like the Session.

The difference between

The difference between cookies and sessions

  • Different storage locations: Cookie data is stored in the client’s browser, while session data is stored on the server
  • The security is different: Cookies are not very secure. Others can analyze cookies stored locally and cheat cookies. For security, session should be used
  • The value types are different: Cookies only support string data. If you want to set other types of data, you need to convert them into strings. Session can store any data type.
  • Different validity periods: Cookies can be set to hold for a long time. For example, the default login function that we often use, the session generally has a short expiration time and will be invalid if the client is closed or the session times out. (There is actually a misunderstanding here, click here for details)
  • Different storage sizes: A single cookie cannot store more than 4K data, and a session can store much more data than cookies

Suggestion: Save important information such as login information as session, and save other information in cookies if necessary

The difference between Token and Session

  • Session is a mechanism for recording the session status between the server and the client. The server is stateful and can record session information. Tokens are tokens, resource credentials needed to access resource interfaces (apis). Token makes the server stateless and does not store session information.
  • Session and Token are not contradictory. As an authentication Token, session security is better than session security, because each request has a signature and can prevent listening and replay attacks, while session must rely on the link layer to ensure communication security. If you need to implement stateful sessions, you can still add sessions to store some state on the server side.
  • Session authentication is simply storing User information in the session. Because of the unpredictability of the sessionID, it is considered safe for the time being. Tokens, if referred to as OAuth tokens or similar mechanisms, provide authentication and authorization, authentication for the user and authorization for the App. The goal is to give an App access to a user’s information. The Token here is unique. It cannot be transferred to other apps, nor can it be transferred to other users. Session provides only a simple authentication, that is, as long as the sessionID is present, the User is considered to have full rights. This data should only be kept on the site and should not be shared with other websites or third-party apps. So to put it simply: If your user data may need to be shared with a third party, or allow a third party to call an API, use Token. If it’s always just your own website, your own App, it doesn’t matter what you use.

conclusion

  • A cookie is like a token with a sessionId stored on the client and usually added automatically by the browser.
  • The session is stored on the server as a list of states with a unique identifier sessionId, usually stored in cookies. After receiving the cookie, the server parses the sessionId and searches the session list to find the corresponding session. Rely on a cookie.
  • Token is also like a token, stateless, the user information is encrypted into the token, the server received the token decrypted to know which user. It needs to be added manually by the developer.

Afterword.

This article is the nature of notes, refer to the data of all parties, thank them for their efforts here, if there are mistakes, please correct the article.

By the way, it’s fast Dragon Boat Festival. Are there any mountaineering parties

Cookie, Session, Token, JWT, do you really understand Cookie and Session, why there is a Session with Cookie

This article is formatted using MDNICE