Thoroughly understand Cookie, Session, JWT and Token (strongly recommended)

Introducing: http is a stateless protocol? How to solve it?

Stateless means that the protocol has no memory capability for transaction processing . The lack of state means that if previous information is required for subsequent processing, it must be retransmitted, potentially resulting in an increased amount of data transferred per connection. The stateless nature of HTTP seriously hinders the implementation of these applications. After all, interaction needs to be a link between the past and the future. A simple shopping cart program also needs to know what products the user has selected before. As a result, two techniques for maintaining the state of the HTTP connection came into being, one is Cookie, and the other is Session.

1. Cookies and Sessions

The cookie can be used to save some user information returned by the server, and each request will carry these cookies. When the server obtains the information in the cookie from the request header, it can identify the source of the request, and http becomes stateful.

Since the solution of maintaining state on the server side also needs to save an identifier on the client side, the session mechanism may need to use the cookie mechanism to achieve the purpose of saving the identifier. Cookies are not very secure. Others can analyze the cookie stored locally and perform cookie deception. Considering the security, the session should be used, and the session will be saved on the server for a certain period of time. When the number of visits increases, it will take up the performance of your server. In order to reduce the performance of the server, you should use cookies.

1.1 Notes on cookies:

1、Cookies are stored on the client side (browser side), so it is not safe and can be cleared by humans. A cookie is a small piece of data that the server sends to the user's browser and saves it locally. It will be carried and sent to the server the next time the browser makes a request to the same server.
2,Cookies have expiration time settings. If the expiration time is not set, it means that the cookie is the session time of the current browser. When the browser is closed, the cookie does not exist. If there is an expiration time, the cookie will be stored on the hard disk, and closing the browser will not affect the cookie. The next time you open the browser, the cookie still exists
3.Cookies can be disabled by the user
4、Cookies have a size limit, the maximum number of cookies a browser can create is 300, and each cannot exceed 4KB , and the total number of cookies that can be set by each Web site cannot exceed 20.
5.Cookies are not cross-domain: Each cookie will be bound to a single domain name, which cannot be obtained and used under other domain names. Shared use is allowed between the first-level domain name and the second-level domain name (relying on the domain).

1.2 Important attributes of cookies

property name describe
String name The name of this cookie . Once the cookie is created, the name cannot be changed, it must be a string type
Object value The value of this cookie . If the value is a Unicode character, it needs to be the character encoding. If the value is binary data, you need to use BASE64 encoding
int maxAge The expiration time of the cookie , in seconds. If positive, the cookie expires after maxAge seconds. If it is a negative number, the cookie is a temporary cookie, which will be invalid after closing the browser, and the browser will not save the cookie in any form. If it is 0, it means to delete the cookie. Defaults to –1.better than expires
int expires Set the cookie expiration time , the cookie will expire after a certain time set.
boolean secure Whether the cookie is only transmitted using a secure protocol . Security Protocol. Security protocols include HTTPS, SSL, etc., which encrypt data before transmitting it on the network. Defaults to false.When the secure value is true,Cookies are invalid in HTTP, only valid in HTTPS
String path The usage path of this cookie . If set to "/love/", only programs whose contextPath is "/love" can access the cookie. If it is set to "/", the contextPath under this domain name can access the cookie. Note that the last character must be "/"
String domain Determines which domain the cookie will be used for . Default is the current domain name
int version The version number used by this cookie . 0 means follow Netscape's cookie specification, 1 means follow W3C's RFC 2109 specification
HttpOnly The cookie cannot be read by js , but the cookie can still be manually modified in the Application, so it only prevents XSS attacks to a certain extent, and is not absolutely safe

1.3 Session Notes:

1、Session is to store user information on the server, If there are more and more users accessing the server, there will be more and more sessions on the server, and the session will put pressure on the server and affect the load of the server. If the content of the session is too complex, when a large number of clients access the server, it may also cause Out of memory.
2,If the user information is lost, or if the user is not accessing this server, the database will be lost.. That's its downside. Now there are some technologies, such as session sharing, iphash, session persistence, etc., which can also solve the above problems.
3.When cookies are disabled, sessions are also disabled. A cookie is just one way to implement a session. Although the most commonly used, it is not the only method. There are other ways to store after disabling cookies, such as putting them in the url.
4. The session is implemented based on cookies, the session is stored on the server side, and the sessionId will be stored in the client's cookie
insert image description here
According to the above process, we can see that SessionID is a bridge connecting Cookie and Session , and most systems also verify the user's login status based on this principle. But the biggest problem with this model is that without a distributed architecture, it cannot support horizontal scaling . If using a server, this mode is completely fine. However, if it is a server cluster or a service-oriented cross-domain architecture, a unified session database library is needed to save session data and share it, so that each server under load balancing can correctly authenticate user identities.
To solve this problem, we can use token, see the explanation of token below

1.4 The difference between Cookie and Session:

Based on the above explanation, let's finally summarize their general differences:
Security: Session is more secure than Cookie, Session is stored on the server side, and Cookie is stored on the client side.
The types of access values ​​are different : Cookie only supports storing string data, and Session can store any data type.
Different validity periods: Cookies can be set to be kept for a long time, such as remember me (default login) and other functions that we often use . Session generally expires for a short time, and the client closes (by default) or the session times out.
The storage size is different: the data saved by a single cookie cannot exceed 4K, and the session can store much more data than a cookie, but when there are too many visits, it will take up too much server resources.

Note:
Most of them are Session + Cookie now, but only session without cookie, or only cookie without session, can theoretically maintain the session state. However, in practice, due to various reasons, it is generally not used alone. If only cookie is used without session, then all account information is stored on the client side. Once hijacked, all information will be leaked. And the amount of client data becomes larger, and the amount of data transmitted over the network also becomes larger.
Using session only needs to save an id on the client side. In fact, a large amount of data is saved on the server side. If all cookies are used, the client does not have so much space when the amount of data is large.
In short, the session is like a user information table, which contains the user's information (name, status, etc.). The cookie is the user pass

2. token (token)

Token, as its name implies, is a token, a certificate, and a key. Only with this key, you can open the door . Tokens are generally generated by the server, such as a web system. When the user logs in, after the server verifies the username and password, a token will be generated, and then the token will be returned to the client, and the client will save the token (put into the HTTP Header), all subsequent requests will carry this token. The server will determine whether the current token exists and has expired. If the token does not exist or expires, the request will be rejected.

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 into a hexadecimal string of a certain length by a hash algorithm)

2.1 Token Advantages

1.Token is completely managed by the application, so it can avoid the same-origin policy
2.safety. Token can avoid CSRF attacks (because cookies are not needed)
CSRF attacks (cross-site request forgery) : attackers steal your identity and send malicious requests in your name . The things that CSRF can do include: send emails in your name, send messages, steal your account, even buy goods, transfer virtual currency... The problems caused include: personal privacy leakage and property security. (If you want to know what the CSRF attack is, you can discuss it in the comment area)
3.Stateless and scalable, which can be shared among multiple services
4.Multi-platform cross-domain: When CORS (Cross-Origin Resource Sharing) extends applications and services, various devices and applications need to be involved. As long as the user has an authenticated token, data and resources can be requested on any domain.

2.2 Token authentication process

insert image description here

3. Token authentication scheme based on JWT

When creating a token, we can set some options. But the standard usage will be shortened in JSON Web TokensJWTreflect.
JSON Web Token (JWT) is currently the most popular cross-domain authentication solution.

3.1 JWT Components

A JSON Web Tokens token consists of three parts in compact form, separated by dots (. ), which are:

Header: Header
Payload: Payload
Signature: Signature

insert image description here
The object is a very long string, and the characters are divided into three substrings by the "." separator.
Each substring represents a functional block, and there are three parts in total: JWT header, payload and signature

3.1.1 Header: Header

The header usually consists of two parts: the type of token (i.e. JWT) and the signature algorithm used, such as HMAC SHA256 or RSA.
E.g:

 此JSON被Base64Url编码以形成JWT的第一部分。
{
    
    
"alg": "HS256",表示签名使用的算法,默认为HMAC SHA256(写为HS256)
"typ": "JWT"表示令牌的类型,JWT令牌统一写为JWT
}

3.1.2 Payload: Payload

The payload part is the main content part of the JWT, and it is also a JSON object that contains the data to be passed. JWT specifies seven default
fields to choose from.

iss: issuer
exp: expiration time
sub: subject
aud: user
nbf: unavailable until then
Iat: issue time
jti: JWT ID used to identify this JWT

In addition to the above default fields, we can also customize private fields, an example payload can be:

{
    
    
"sub": "9876543210",
"name": "Mr Fen",
"admin": true
请注意,默认情况下JWT是未加密的,任何人都可以解读其内容,因此不要构建隐私信息字段,存放保密信息,以防止信息泄露。
}

3.1.3 Payload: Signature

To create the signed part, you must get the encoded header, the encoded payload, the key, the algorithm specified in the header, and sign it.
For example, if you were to use the HMAC SHA256 algorithm, the signature would be created in the following way:

HMACSHA256(base64UrlEncode(header) + "." + base64UrlEncode(claims), secret)

3.2 When should JWT be used?

1. Authentication, which is the most common scenario for using JWT . Once the user is logged in, each subsequent request will include the JWT, allowing the user to access routes, services and resources allowed by that token. Single sign-on is a feature that is widely used today with JWT because it has little overhead and can be easily used across different domains.
2. Information exchange, JWT tokens are a great way to securely transfer information between parties . Because the JWT can be signed (eg, with a public/private key pair), you can be sure that the sender is who you are. Also, since the signature is calculated using the header and payload, you can also verify that the content has not been tampered with.

3.3 What is the relationship between JWT and Token?

A token is a string generated according to certain rules and contains user information.
Generally, we will use the standard usage JWT.
JWT is to prescribe rules for us. Using JWT, we can generate strings that contain user information.

Guess you like

Origin blog.csdn.net/weixin_46015018/article/details/122667394