Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is Cookie, Session, Token, JWT

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly introduces "what is Cookie, Session, Token, JWT". In daily operation, I believe many people have doubts about what is Cookie, Session, Token and JWT. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the questions of "what is Cookie, Session, Token, JWT"! Next, please follow the editor to study!

What is certification (Authentication)

In popular terms, it is to verify the identity of the current user and prove that "you are yourself" (for example, when you punch in every day, you need to punch in through your fingerprints, and when your fingerprints match those entered in the system, you sign in successfully)

Authentication in the Internet:

Login with username and password

The mailbox sends a login link

The mobile phone number receives the verification code

As long as you can receive the email / CAPTCHA, you will default to be the owner of the account.

What is authorization (Authorization)

The user grants third-party applications access to some of the user's resources

When you install a mobile app, APP will ask if you are allowed to grant permissions (access to photo albums, geographic locations, etc.)

When you visit WeChat Mini Programs, when you log in, Mini Program will ask if permission is allowed to be granted (get nickname, profile picture, region, gender and other personal information).

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

What is a certificate (Credentials)

The premise of authentication and authorization is that a medium (certificate) is needed to mark the identity of the visitor.

During the warring States period, Shang Yang reformed and invented the personal post. The poster, issued by the government, is a smooth and fine bamboo board engraved with the holder's profile picture and place of origin information. Chinese people must hold it, if not, it will be considered as a household registration is not registered, or spies and so on.

In real life, everyone will have an exclusive identity card, which is a legal document used to prove the identity of the holder. Through the ID card, we can apply for mobile phone card / bank card / personal loan / transportation travel and so on. This is the certificate of authentication.

In Internet applications, general websites (such as Nuggets) have two modes, the tourist mode and the login mode. In visitor mode, you can browse the articles on the site normally. Once you want to like / collect / share articles, you need to log in or sign up for an account. When the user logs in successfully, the server will issue a token to the browser used by the user, which is used to indicate your identity. Each time the browser sends a request, the server will bring this token with it, and you can use functions that cannot be used in visitor mode.

What is Cookie?

HTTP is a stateless protocol (no memory for transactions, and the server will not save any session information each time the client and server session is completed): each request is completely independent, and the server cannot confirm the identity information of the current visitor and cannot tell whether the sender of the last request and the sender of this time are the same person. So in order to track the session (knowing who is visiting me), the server and browser must actively maintain a state that tells the server whether the two requests come from the same browser. This state needs to be achieved through cookie or session.

Cookie is stored on the client: a cookie is a small piece of data sent by the server to the user's browser and saved locally, which is carried and sent to the server the next time the browser makes another request to the same server.

Cookie cannot be cross-domain: each cookie is bound to a single domain name and cannot be obtained and used under other domain names. Sharing between first-level and second-level domain names is allowed (depending on domain).

The important attributes of cookie state that the name=value key-value pair, setting the name of Cookie and the corresponding value must be a string type.

If the value is a Unicode character, you need to encode the character.

If the value is binary data, you need to use BASE64 encoding. Domain specifies the domain name to which cookie belongs. By default, the current domain name path**** specifies the path (route) under which cookie takes effect. The default is'/'. If set to / abc, only routes under / abc can access the cookie, such as: / abc/read. The time of maxAgecookie invalidation (in seconds). If an integer, the cookie expires after maxAge seconds. If it is a negative number, the cookie is a temporary cookie, the browser closes, and the browser does not save the cookie in any form. If 0, the cookie is deleted. The default is-1.

Better than expires. When the expires expires, the cookie will expire after a certain point in time. In general, the cookie of a browser is stored by default. When you close the browser to end the session, the cookie will be deleted secure whether the cookie is only transmitted using the security protocol. Security protocols such as HTTPS,SSL encrypt the data before transmitting it on the network. The default is false. When the secure value is true, cookie is not valid in HTTP, but is valid in HTTPS. If httpOnly**** sets the httpOnly attribute to a cookie, the information of the cookie cannot be read through the JS script, but the cookie can still be manually modified through the Application, so it can only prevent XSS attacks to a certain extent, not absolute security.

What is Session?

Session is another mechanism for recording server and client session state

Session is implemented based on cookie, session is stored on the server side, and sessionId is stored in the cookie on the client side.

Session.png

Session certification process:

When the user requests the server for the first time, the server creates the corresponding Session based on the relevant information submitted by the user

Return the unique identification information of this Session, SessionID, to the browser when the request is returned.

When the browser receives the SessionID information returned by the server, it stores the information in the Cookie, and the Cookie records which domain name the SessionID belongs to.

When the user visits the server for the second time, the request will automatically determine whether the Cookie information exists under this domain name. If so, the server will automatically send the Cookie information to the server, and the server will obtain the SessionID from the Cookie, and then find the corresponding Session information according to the SessionID. If it is not found, it means that the user has not logged in or the login is invalid. If the Session is found to prove that the user has logged in, you can perform the following actions.

According to the above process, SessionID is a bridge between Cookie and Session, and most systems also verify the login status of users according to this principle.

The difference between Cookie and Session

Security: Session is more secure than Cookie. Session is stored on the server side and Cookie on the client side.

The type of access value is different: Cookie only supports storing string data. If you want to set other types of data, you need to convert it to a string. Session can store any data type.

The validity period is different: Cookie can be set to be maintained for a long time, such as the default login feature we often use. Session generally has a short expiration time, client shutdown (by default) or Session timeout will expire.

Storage size is different: a single Cookie cannot store more than 4K data. Data can be stored in a session much higher than Cookie, but when there are too many visits, it will take up too much server resources.

What is Token (token)

Acesss Token

Resource credentials required to access the resource interface (API)

The composition of simple token: uid (unique identity of the user), time (timestamp of the current time), sign (signature, the first few bits of token are compressed into a certain length hexadecimal string by hashing algorithm)

Features:

The server is stateless and scalable.

Support for mobile devices

Safety

Support for cross-program calls

Authentication process for token:

Hongmeng official Strategic Cooperation to build HarmonyOS Technology Community

The client requests login with a user name and password

The server receives a request to verify the user name 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 cookie or localStorage

Each time the client requests resources from the server, it needs to bring the token signed by the server.

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

Token is required for each request, and token needs to be placed in the Header of HTTP.

User authentication based on token is a stateless authentication method on the server side, and the server side does not need to store token data. Exchange the computing time of parsing token for the storage space of session, so as to reduce the pressure on the server and reduce the frequent query of database.

Token is completely managed by the application, so it can avoid the same origin policy

Refresh Token

Another kind of token--refresh token

Refresh token is a token dedicated to refreshing access token. If there is no refresh token, you can also refresh the access token, but each refresh requires the user to enter a login user name and password, which will be troublesome. With refresh token, this hassle can be reduced, and the client directly updates the access token with refresh token without the need for additional operations by the user.

The validity period of Access Token is relatively short. When the Acesss Token expires due to expiration, you can use Refresh Token to get the new Token. 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's database and are verified only when you apply for a new Acesss Token, which does not affect the response time of the business interface, and does not need to be kept in memory to deal with a large number of requests like Session.

The difference between Token and Session

Session is a mechanism to record the session state of the server and the client, which makes the server stateful and can record the session information. Token is the token, the resource credential required to access the resource interface (API). Token makes the server stateless and does not store session information.

There is no contradiction between Session and Token. As an authentication Token, security is better than Session, because every request has a signature and can prevent snooping and replay attacks, and Session must rely on the link layer to ensure communication security. If you need to implement stateful sessions, you can still add Session to save some state on the server side.

The so-called Session authentication is simply to store User information in Session. Because of the unpredictability of SessionID, it is considered to be secure for the time being. Token, if it refers to OAuth Token or similar mechanisms, provides authentication and authorization, authentication is for users, authorization is for App. The purpose is to give an App access to a user's information. The Token here is unique. Cannot be transferred to other App, nor to other users. Session only provides a simple authentication, that is, as long as there is this SessionID, it is considered to have all the rights to this User. This data should be kept strictly confidential and should not be shared with other websites or third party App. So to put it simply: if your user data may need to be shared with third parties, or allow third parties to call the API interface, use Token. If it is always just your own website, your own App, it doesn't matter what you use.

What is JWT?

JSON Web Token (JWT for short) is the most popular cross-domain authentication solution at present.

It is an authentication and authorization mechanism.

JWT is an open standard based on JSON (RFC 7519) that is implemented to communicate declarations between network application environments. JWT declarations are generally used to pass authenticated user identity information between identity providers and service providers in order to obtain resources from the resource server. For example, it is used in user login.

JWT can be signed using the HMAC algorithm or the public / private key of RSA. Because of the existence of digital signatures, these messages are credible.

Teacher Ruan Yifeng's introduction to JSON Web Token is very easy to understand, so there is no longer a lesson here.

Generate JWT

Jwt.io/www.jsonwebtoken.io/

The principle of JWT

JWT certification process:

The user enters the user name / password to log in. After the server authentication is successful, it will return a JWT to the client.

The client saves the token locally (usually using localstorage, or you can use cookie)

When users want to access a protected route or resource, they need to add JWT using Bearer mode in the Authorization field of the request header, which looks like this

Authorization: Bearer copy code

The server's protection route will check the JWT information in the request header Authorization and, if legal, allow the user's behavior.

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

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

Because the user's state is no longer stored in the server's memory, this is a stateless authentication mechanism.

How to use JWT

The client receives the JWT returned by the server, which can be stored in Cookie or localStorage.

Mode one

When users want to access a protected route or resource, they can send it automatically in Cookie, but this cannot be cross-domain, so it is better to put it in the Authorization field of HTTP request header information and use Bearer mode to add JWT.

GET / calendar/v1/events Host: api.example.com Authorization: Bearer

The user's status is not stored in the server's memory, which is a stateless authentication mechanism.

The server's protection route will check the JWT information in the request header Authorization and, if legal, allow the user's behavior.

Because JWT is self-contained, it reduces the need to query the database

These features of JWT allow us to rely entirely on its stateless nature to provide data API services, or even to create a download stream service.

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

Mode two

When cross-domain, you can put JWT in the data body requested by POST.

Mode 3

Transmit through URL

Http://www.example.com/user?token=xxx

Using JWT in a project

* * Project address: https://github.com/yjdjiayou/jwt-demo * *

The difference between Token and JWT

Same:

All are tokens to access resources.

Can record the user's information.

It all makes the server stateless.

Only after successful verification can the client access the 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: Token and Payload are encrypted and stored in the client, and the server only needs to use key decryption to verify (the verification is also implemented by JWT itself). There is no need to query or reduce the query database, because JWT contains user information and encrypted data.

Common front and rear authentication methods

Hongmeng official Strategic Cooperation to build HarmonyOS Technology Community

Session-Cookie

Token authentication (including JWT,SSO)

OAuth3.0 (Open Licensing)

Common encryption algorithms

Image.png

Hash algorithm (Hash Algorithm), also known as hash algorithm, hash function, hash function, is a method to create small digital "fingerprints" from any kind of data. The hash algorithm remixes the data and recreates a hash value.

The hash algorithm is mainly used to ensure the authenticity of the data (that is, integrity), that is, the sender sends the original message with the hash value, and the recipient verifies the authenticity of the original data through the same hash function.

Hashing algorithms usually have the following characteristics:

Positive fast: hash values can be quickly calculated from raw data

Reverse difficulty: it is almost impossible to derive the original data from the hash value.

Input sensitivity: as long as there is a little change in the original data, the hash value is very different.

Conflict avoidance: it is difficult to find different raw data to get the same hash, and the number of atoms in the universe is about 10 to 60 to 80, so 2 to 256 has enough space to accommodate all possibilities. when the algorithm is good, the probability of collision is very low:

The 128 power of 2 is 3402823669209384663374607431768211456, that is, 10 to the 39th power.

The 160th power of 2 is 1.4615016373309029182036848327163e+48, which is the 48th power of 10.

The 256 power of 2 is 1.1579208923731619542357098500869 × 10 to the 77th power, which is 10 to the 77th power.

Note:

The above cannot guarantee that the data has been maliciously tampered with, and the original data and hash value may be maliciously tampered with. To ensure that it will not be tampered with, we can use the RSA public key and private key scheme together with the hash value.

The hash algorithm is mainly used to prevent errors in the process of computer transmission. in the early days, the computer is guaranteed by the first 7-bit data, the eighth bit parity code (12.5% waste and low efficiency). For a piece of data or file, the hash value of 128bit or 256bit is generated by the hash algorithm, and it is required to retransmit if there is something wrong with the verification.

common problem

Issues to consider when using cookie

Because it is stored in the client, it is easy to be tampered with by the client, so you need to verify the validity before using it.

Do not store sensitive data, such as user passwords and account balances

Using httpOnly to improve security to a certain extent

Reduce the volume of cookie as much as possible, and the amount of data that can be stored cannot exceed 4kb

Set up the correct domain and path to reduce data transmission

Cookie cannot cross domain

A browser can store up to 20 Cookie for a website. Generally speaking, browsers are only allowed to store 300 Cookie.

Mobile support for cookie is not very good, and session needs to be implemented based on cookie, so token is commonly used on mobile.

Issues to consider when using session

When the session is stored in the server, when the user has a large amount of online at the same time, these session will occupy more memory and need to clean up the expired session regularly on the server.

When a website is deployed in a cluster, it will encounter the problem of how to share web among multiple session servers. Because the session is created by a single server, but the server that handles the user's request is not necessarily the server that created the session, the server cannot get information such as login credentials that have been put into the session.

When multiple applications want to share session, in addition to the above problems, they will also encounter cross-domain problems, because different applications may deploy different hosts, so cookie cross-domain processing needs to be done in each application.

SessionId is stored in cookie, what if the browser forbids cookie or does not support cookie? Generally speaking, sessionId is followed by the url parameter to rewrite url, so session does not have to be implemented by cookie.

Mobile support for cookie is not very good, and session needs to be implemented based on cookie, so token is commonly used on mobile.

Issues to consider when using token

If you think that using a database to store token will cause the query time to be too long, you can choose to put it in memory. For example, redis suits your needs for token queries.

Token is completely managed by the application, so it can avoid the same origin policy

Token can avoid CSRF attacks (because cookie is no longer needed)

Mobile support for cookie is not very good, and session needs to be implemented based on cookie, so token is commonly used on mobile.

Issues to consider when using JWT

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

JWT is not encrypted by default, but it can be encrypted. After the original Token is generated, it can be encrypted again with the key.

Secret data cannot be written to JWT without JWT encryption.

JWT can be used not only for authentication, but also for the exchange of information. Effective use of JWT can reduce the number of times the server queries the database.

The biggest advantage of JWT is that the server no longer needs to store Session, which makes the server authentication and authentication business easy to expand. But this is also the biggest disadvantage of JWT: because the server does not need to store Session state, you cannot discard a Token or change the permissions of Token during use. That is, once the JWT is signed, it will remain valid until it expires, unless the server deploys additional logic.

JWT itself contains authentication information, and once disclosed, anyone can get all the privileges of the token. To reduce embezzlement, the validity period of JWT should be set to be short. For some of the more important permissions, users should be authenticated again when using them.

JWT is suitable for one-time command authentication, issuing a JWT with a very short validity period, even if the risk is very small. Since a new JWT is generated for each operation, it is not necessary to save the JWT to achieve statelessness.

In order to reduce embezzlement, JWT should not use the HTTP protocol for plain code transmission, but should use the HTTPS protocol for transmission.

Problems to be considered when using encryption algorithms

Never store passwords in clear text

Always use hashing algorithms to deal with passwords. Never use Base64 or other encoding to store passwords, which is the same as storing passwords in clear text. Use hashes instead of encodings. Encoding and encryption are two-way processes, while passwords are confidential and should be known only to its owners, and the process must be one-way. Hash is used to do this, never solve the term hash, but encoding there is decoding, encryption there is decryption.

Never use a weak hash or a cracked hash algorithm, such as MD5 or SHA1, only use a strong password hash algorithm.

Never display or send passwords in clear text, even for the owner of the password. If you need the "forget password" function, you can randomly generate a new one-time (which is important) password and send it to the user.

Session sharing Scheme under distributed Architecture

1. Session replication

When the session on any server changes (add, delete, modify), the node serializes all the contents of the session and broadcasts it to all other nodes, regardless of whether the other servers need session or not, in order to ensure session synchronization

Advantages: fault-tolerant, session between servers can respond in real time.

Disadvantages: it will cause some pressure on the network load, and if the amount of session is large, it may cause network congestion and slow down the server performance.

two。 Sticky session / IP binding strategy

Using the ip_hash mechanism in Ngnix, all requests from an ip are directed to the same server, that is, the user is bound to the server. When the user requests for the first time, the load balancer forwards the user's request to server A. If the load balancer sets sticky session, then every subsequent request of the user will be forwarded to server A, which is equivalent to gluing the user and server A together. This is the sticky session mechanism.

Pros: it is simple and does not require any processing of session.

Disadvantages: lack of fault tolerance, if the current access to the server failure, the user is transferred to the second server, his session information will be invalid.

Applicable scenario: failure has little impact on the customer; server failure is a low-probability event. Implementation: taking Nginx as an example, the sticky session can be realized by configuring the ip_hash attribute in the upstream module.

3. Session sharing (commonly used)

Use distributed caching schemes such as Memcached and Redis to cache session, but Memcached or Redis must be a cluster

Although storing session in Redis becomes architecturally complex and requires one more access to Redis, the benefits of this solution are also great:

Session sharing is realized.

Can scale horizontally (add Redis servers)

Server restart session is not lost (but also pay attention to the refresh / failure mechanism of session in Redis)

Can be shared not only across server session, but also across platforms (such as web side and APP side)

4. Session persistence

Store session in the database to ensure the persistence of session

Pros: if there is a problem with the server, session will not be lost

Disadvantages: if the site has a large number of visitors, storing session in the database will put a lot of pressure on the database and require additional overhead to maintain the database.

As soon as you close the browser, session really disappears?

Wrong. For session, unless the program tells the server to delete a session, the server will keep it all the time. The program usually sends an instruction to delete the session when the user does the log off. However, the browser never actively notifies the server that it is going to shut down before shutting down, so the server will never have a chance to know that the browser has been closed. The reason for this illusion is that most session mechanisms use session cookie to save the session id, but after closing the browser, the session id disappears, and the original session cannot be found when you connect to the server again. If the cookie set by the server is saved on the hard disk, or if you use some means to rewrite the HTTP request header issued by the browser and send the original session id to the server, you can still open the original session by opening the browser 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 expiration time is longer than the last time the client uses session, the server thinks that the client has stopped its activity and will delete the session to save storage space.

At this point, the study of "what is Cookie, Session, Token, JWT" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report