Understand the differences between cookies, Session, Token, and JWT in one article

1. What is Authentication

In layman’s terms, it is to verify the identity of the current user and prove that “you are yourself” (for example: when you clock in and out every day, you need to clock in with your fingerprint. When your fingerprint matches the fingerprint entered in the system, the clock in is successful) .

Authentication on the Internet

Login with username and password

Email login link

Mobile phone number to receive verification code

As long as you can receive the email/verification code, you are the owner of the account by default

2. What is Authorization

A user grants a third-party application permission to access certain resources of the user.

When you install the mobile app, the APP will ask whether to grant permissions (access to photo albums, geographical location, etc.)

When you access the WeChat mini program, when you log in, the mini program will ask whether you are allowed to grant permissions (obtain personal information such as nickname, avatar, region, gender, etc.)

The ways to implement authorization are: cookie, session, token, OAuth

3. What are Credentials

Credentials are the prerequisite for authentication and authorization. They are a medium (positive number) used to identify visitors.

During the Warring States Period, Shang Yang carried out his reform and invented the Zhao Shen Tie. The photo sticker is issued by the government and is a smooth and finely polished bamboo board with the holder’s profile picture and place of birth engraved on it. Chinese people must have it. If they don’t have it, they are considered to be undercover, or spies.

In real life, everyone will have an exclusive resident ID card, which is a legal document used to prove the identity of the holder. Through the ID card, we can apply for mobile phone cards/bank cards/personal loans/transportation, etc. This is the certified certificate.

In Internet applications, general websites (such as Nuggets) have two modes, guest mode and login mode. In guest mode, you can browse the articles on the website normally. Once you want to like/collect/share articles, you need to log in or register an account. When the user logs in successfully, the server will issue a token to the browser used by the user. This token is used to indicate your identity. Each time the browser sends a request, it will bring this token with you and you can use it. Features not available in guest mode.

Session management

4.What is cookie

4.1 What is a stateless protocol

Encyclopedia explanation: The stateless protocol means that for example, the customer closes the browser after obtaining a web page, then starts the browser again, and then logs in to the website, but the server does not know that the customer closed the browser once. There is no memory capability for transaction processing. Each time the session between the client and the server is completed, the server will not save any session information, that is, the next link will not remember the information of this link.

4.2. What is a stateful protocol

Both communicating parties need to remember each other to share information. My personal understanding is: it records the information of both parties in the communication. Use an inappropriate example to illustrate who I am, where I am, where I come from, and where I am going.

4.3. The difference between stateful protocols and stateless protocols

Does the implementation of the protocol require the client or server to maintain a state. For example, tcp transmission requires a handshake to initialize transactions (data integrity verification, etc.), so it is stateful; obviously the http protocol itself does not require this, and cookies or sessions are browsers and servers on top of the http protocol. Status tags are implemented by adding certain agreed fields to each request that does not have status. HTTP uses the browser’s session and cookie to determine whether the user is logged in or not logged in, and sends different web pages to the browser based on the difference between the two states.

The “state” in the machine can be understood as “memory”. State corresponds to memory, and statelessness corresponds to no memory. Normal people have memories and can remember people and things in daily life. Memory is stored in brain cells, which is stateful. Some people suffer from amnesia or amnesia, unable to remember what happened, and their minds go blank. This is statelessness.

A stateful protocol means that both communicating parties must remember both parties and share some information. The communication of the stateless protocol is independent every time and has nothing to do with your last communication.

In human terms, when you go out with friends, you don’t have to give your name and contact information every time so your friends know who you are. This is status; when you go to the service hall, the staff will not remember who you are. You have to fill out a form and show your ID card every time, which is stateless.

After understanding what stateless protocols and stateful protocols are, the following introduction will be easy to understand.

4.4. What is Cookie

HTTP is a stateless protocol: each request is completely independent. The server cannot confirm the identity of the current visitor, and cannot identify whether the sender of the last request is the same person as this one. In order to track sessions (know who is visiting me), the server and browser must actively maintain a state. This state is used to tell the server whether the two requests before and after are from the same browser. This state is achieved through cookies and sessions. In this way, the stateful purpose is achieved. Cookies are also variables and are used to store key-value pairs, very similar to sessions.

4.5.Cookies are stored on the client

A cookie is a small piece of data sent by the server to the user’s browser and saved locally. It will be carried and sent to the server the next time the browser sends a request to the same server. After receiving the request, the server can obtain the cookie from the request header and then perform operations; add the modified cookie to the response and send it to the client; the client receives the response cookie and automatically updates the original cookie. . The cookie is stored on the client, but the server code can operate it, and the js code can also operate document.cookie to obtain the cookie.

4.6. Cookies are not cross-domain

Each cookie will be bound to a single domain name and cannot be obtained from other sources. Sharing between first-level domain names and second-level domain names is allowed (depending on the domain).

4.7. Cookie usage scenarios
1) Remember me

2) Unlogged shopping cart

5. What is Session

Server-side applications are usually based on the HTTP protocol. The HTTP protocol itself is a “stateless” protocol, so it cannot save the state of the client. For example, it cannot identify the client’s identity, so even if the same client multiple times When accessing the same server, the server does not recognize that it is the client that visited before!

In development practice, it is mostly necessary to be able to identify the client’s identity, which can usually be solved using the Session mechanism!

When a client accesses a server for the first time, it will directly initiate a request. When the server receives this request, it will return a Session ID value (essentially a UUID value) in the response. When the client receives After receiving the Session ID, subsequent visits will automatically carry this Session ID to the server, and the server can identify the client’s identity based on this Session ID value.

On the server side, the K-V structure data is used to represent the Session. The Session ID carried by the client is the Key in the K-V structure. Therefore, each client can access a different Value, that is, the Session data corresponding to each client.

Session is data stored in the server-side memory, and memory resources are relatively limited resources and the storage space is relatively small. Therefore, there must be a mechanism to clear Session. The default clearing mechanism is “automatic clearing over timeout”, that is, a client After the last request submitted by the client, if no request is submitted again within a certain period of time, the server will clear the Session data corresponding to this client! As for how long it takes to clear the session, there is no clear requirement. The default time of most software is 15 to 30 minutes, but it can also be set to a shorter or longer time.

Based on the characteristics of Session, usually, most of the data stored in Session is:

  • Identification of the user’s identity, such as the ID of the logged in user

  • Frequently accessed data, such as usernames of logged in users

  • Data that is not easy/convenient to use other storage mechanisms, such as verification codes

At the same time, Session also has some shortcomings:

  • Not suitable for storing large amounts of data

    • This problem can be avoided through disciplined development

  • Not easy to apply to clusters or distributed systems

    • This problem can be solved by sharing the Session

  • Cannot be stored for a long time

    • No solution

  • What is saved through session management technology is the data between the client and the server, not the data between the user and the server.

    • Session management saves data related to the client

    • The database stores data related to users

5.1. As long as you close the browser, will the session really disappear?

wrong. For sessions, unless the program notifies the server to delete a session, the server will keep it. The program usually sends an instruction to delete the session when the user logs off. However, the browser never actively notifies the server that it is about to close before closing, so the server has no chance to know that the browser has been closed. The reason for this illusion is that most session mechanisms use session cookies to save session ids. , and the session id disappears after closing the browser, and the original session cannot be found when connecting to the server again.

If the cookie set by the server is saved on the hard disk, or some method is used to rewrite the HTTP request header sent by the browser and send the original session id to the server, the original session can still be opened when the browser is opened again. It is precisely because closing the browser will not cause the session to be deleted, forcing the server to set an expiration time for the session. When the time since the client last used the session exceeds this expiration time, the server will consider that the client has stopped activities. The session will be deleted to save storage space.

6. What is the difference between Cookie and Session?

Cookie: Data is saved on the client (similar to a punched membership card)

  • Storage time: Cookies are stored in the browser’s memory by default. The data will be cleared when the browser is closed. You can also set any storage time. If the storage time is set, the cookie data will be stored in the client’s disk until the storage time expires. will be cleared automatically.

  • Data type: Cookie can only save string data

  • Application scenarios: Mainly used in scenarios where data needs to be saved for a long time, such as: remembering usernames and passwords

Session: Data is saved on the server (similar to bank card)

  • Saving time: The default saving interval is only half an hour. Since all client data is saved in the memory of a server, the server’s memory resources are relatively tight, so it cannot be saved for too long.

  • Data type: can save data of any object type

  • Application scenarios: Mainly used in scenarios with high security requirements, such as: login status

7. What is Token

Token: Token, ticket

The Token mechanism is used to solve the problem of server-side identifying the client’s identity.

When using the Token mechanism, when the client submits a request to the server for the first time, or when submitting a login request, the client directly sends the request to the server without special processing, and the server will process the request on demand (for example, If the client submits a login request, the login is processed), and a Token is generated from the client’s identity data, and this Token is responded to the client. Subsequently, the client needs to carry this Token to submit various requests, and the server will also The client’s identity is identified based on this Token data.

Different from Session, Token is data generated by a server-side program (written by itself) and is a piece of meaningful data. In contrast, the Session ID in the Session mechanism is a UUID value, which only guarantees uniqueness. The data itself is meaningless! Token does not need to have matching data on the server side, because it is data itself!

During the processing, the server only needs to check the Token and parse the client identity-related data from the Token. There is no need to save the Token data in the memory of the server, so the Token can be set to be longer or even very long. It has a long validity period and does not consume the memory resources used to store data on the server side.

At the same time, Token is inherently suitable for clusters or distributed systems, as long as each server has the same program for checking Token and parsing Token.

7.1.Acesss Token
Resource credentials required to access the resource interface (API)

The composition of a simple token: uid (user's unique identity), time (timestamp of the current time), sign (signature, the first few digits of the token are compressed with a hash algorithm)
A hexadecimal string of a certain length)

Features

The server is stateless and has good scalability

Support mobile devices

Safety

Support cross-program calls

Token authentication process:

The client requests login using username and password

The server receives the request to verify the username and password.

After successful verification, the server will issue a token and send the token to the client.

After the client receives the token, it will store it, such as in a cookie or localStorage.

Every time the client requests resources from the server, it needs to bring the token issued by the server.

The server receives the request and then verifies the token contained in the client's request. If the verification is successful, it returns the requested data to the client.

Every request needs to carry a token, and the token needs to be placed in the HTTP Header.

Token-based user authentication is a server-side stateless authentication method, and the server does not need to store token data. The calculation time of parsing the token is exchanged for the storage space of the session.
Thereby reducing the pressure on the server and reducing frequent database queries.

The token is completely managed by the application, so it can avoid the same origin policy
7.2.Refresh Token

Another token–refresh token

refresh token is a token specifically used to refresh access tokens. If there is no refresh token, you can also refresh the access token, but each refresh requires the user to enter the login user name and password, which will be very troublesome. With the refresh token, this trouble can be reduced. The client directly uses the refresh token to update the access token without requiring the user to perform additional operations.

The validity period of Access Token is relatively short. When the Access Token expires due to expiration, a new Token can be obtained by using Refresh Token. If the Refresh Token also expires, the user can only log in again.

The Refresh Token and expiration time are stored in the server’s database and will only be verified when applying for a new Access Token. It will not affect the response time of the business interface and does not need to be kept in memory like the Session to cope with a large number of requests. ask.

8. What is the difference between Token and Session?

Session is a mechanism that records the session status of the server and client, making the server stateful and able to record session information. Token is a token, a resource credential required to access the resource interface (API). Token makes the server stateless and does not store session information.

Session and Token are not contradictory. As an identity authentication Token, the security is better than Session, because each request is signed and can prevent monitoring and replay attacks, while Session must rely on the link layer to ensure communication security. If you need to implement a stateful session, you can still add a Session to save some state on the server side.

The so-called Session authentication simply stores User information in the Session. Because of the unpredictability of SessionID, it is considered safe for the time being. And Token, if it refers to OAuth Token or a similar mechanism, provides authentication and authorization. Authentication is for users, and authorization is for App. The purpose is to give an app the right to access a user’s information.

The Token here is unique. It cannot be transferred to other apps or to other users. Session only provides a simple authentication, that is, as long as there is this SessionID, it is considered that this User has all the rights. It needs to be kept strictly confidential. This data should only be stored 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 the API interface, use Token. If it is always just your own website and your own App, it doesn’t matter what you use.

9.What is JWT?

JWT:JSON Web Token

Official website for generating JWT: JSON Web Tokens – jwt.io

Each JWT data is composed of 3 parts:

  • Header: declares the algorithm and Token type

  • Payload: data

  • Verify Signature: Verify signature

Toolkit for JWT programming: JSON Web Token Libraries – jwt.io

9.1.Principles of JWT

JWT authentication process

The user enters the username/password to log in. After the server authentication is successful, a JWT will be returned to the client;

The client saves the token locally (usually using localstorage, but can also use cookies);

When the user wants to access a protected route or resource, he needs to use the Bearer mode to add JWT in the Authorization field of the request header. The content looks like the following
9.2.Authorization: Bearer
The server-side protection route will check the JWT information in the request header Authorization. If it is legal, the user's behavior will be allowed.

Because JWT is self-contained (contains some session information internally), it reduces the need to query the database

Because JWT does not use cookies, you can use any domain name to provide your API services without worrying about cross-origin resource sharing (CORS)

Because the user's status is no longer stored in the server's memory, this is a stateless authentication mechanism
Advantages of 9.3.jwt:
1. Good scalability. When the application is deployed in a distributed manner, the session needs to be shared among multiple machines, which can usually be stored in a database or redis. And jwt doesn't need it.

2/Stateless, jwt does not store any state on the server side. One of the principles of RESTful API is statelessness. When a request is made, a response with parameters will always be returned without additional impact. The user's authentication status introduces this additional effect, which defeats this principle. In addition, some common information can be stored in the jwt payload for exchanging information. Effective use of JWT can reduce the number of times the server queries the database.

3. The versatility of the json format, so JWT can be supported across languages, such as Java, JavaScript, PHP, Node, etc.

4. Payload can be used to store some non-sensitive information.

5. JWT has a simple structure, small byte usage, and is easy to transmit.

6. There is no need to save session information on the server side, and it is easy to extend the application, especially suitable for distributed microservices. 
Disadvantages of 9.4.jwt:
1. Security cannot be guaranteed, so sensitive data cannot be stored in jwt. Because the jwt payload is not encrypted, it is just Base64 encoded.

2. The law was abandoned midway. Because once a jwt is issued, it is always valid until it expires. If the user information is updated, you can only wait for the old jwt to expire and re-issue a new jwt.

3. Renewal issues. When the issued jwt is saved on the client, the client has been operating the page. Logically, the validity period should be extended for the client. Otherwise, when the jwt validity period expires, the user will need to log in again. So how to renew jwt? The simplest and crudest method is to issue a new jwt every time, but it will affect performance because it is too violent. If you want to be more elegant, you need to introduce Redis to solve it, but this turns the stateless jw t into a stateful one, which violates the original intention. 
10.What is the difference between Token and JWT?
Same as:
They are all tokens for accessing resources.

Can record user information

They all make the server stateless.

Only after successful verification can the client access protected resources on the server
Difference:
Token: When the server verifies the Token sent by the client, it also needs to query the database to obtain user information, and then verify whether the Token is valid.

JWT: The Token and Payload are encrypted and stored on the client. The server only needs to use key decryption for verification (the verification is also implemented by JWT itself). There is no need to query or reduce the query database, because JWT self-contains the user Messages and encrypted data
11.What is the difference between Session and JWT?

The main difference between the session-based and jwt-based methods is the location where the user’s state is saved. The session is saved on the server side, while the jwt is saved on the client side.

The knowledge points of the article match the official knowledge files, and you can further learn related knowledge. Java Skill TreeHomepageOverview 137588 people are learning the system