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

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

Share

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

This article mainly explains "what is Cookie, Session, Token". Friends who are interested may wish to have a look. The method introduced in this paper is simple, fast and practical. Next, let the editor take you to learn "what is Cookie, Session, Token"?

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, fingerprint identification is required when you go to and from work every day and enter or leave the community. If the current fingerprint matches the input in the system library, the authentication is successful.)

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. (it can be understood as our current ID card)

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).

Important attributes of cookie

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 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 exists 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.

Different validity periods: the life cycle of cookie can be passed through cookie.setMaxAge (2000) To set, if setMaxAge is not set, the life cycle of cookie dies when the browser is closed. The life cycle of cookie is cumulative and starts to be timed from the time of creation. 20 minutes later, the life cycle of cookie ends, and the life cycle of session is spaced. From the time of creation, if the time is 20 minutes and there is no access to session, then the life cycle of session is destroyed If the session is accessed within 20 minutes (such as at 19 minutes), the life cycle of the session will be recalculated.

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)

Characteristics

The server is stateless and scalable.

Support for mobile devices

Safety

Support for cross-program calls

Authentication process of token

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

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.

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.

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, I believe you have a deeper understanding of "what is Cookie, Session, Token". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

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