Home>Article>Web Front-end> Node learning talks about the working principle of Cookie-Session login verification
At present, most systems are indispensable for theLogin verificationfunction. This is mainly to save the user's status and limit the user's various behaviors. This makes it convenient and effective to control user permissions. For example, when a user logs in to Weibo, the operations of posting, following, and commenting should be performed under the user statusafterlogin.
There are two main ways to implement login verification:Cookie&Session
andJWT
. In this section we will first discuss theCookie&Session
The working principlewill be introduced in detail. In subsequent articles, we will successively introduceJWT
and how to useCookie&Session
andJWT
to improve what we have learned in the previous sections. The simple user management system built is explained. [Related tutorial recommendations:nodejs video tutorial]
We know that HTTP is stateless. In other words, the HTTP requester and responder cannot maintain state, it is all one-time, and it does not know what happened in the previous and subsequent requests. But in some scenarios, we need to maintain state. Most typically, when a user logs in to Weibo, posts, follows, and comments should be under the user statusafterlogin.
At this time,Cookie
andSession
can be introduced to save the user's login status.
This article mainly introduces the
working principle of using
Cookie-Sessionfor login verification, aboutCookie
andFor a detailed introduction to Session
, please refer to this guy’s article:Cookie and Session Detailed Explanation
Cookie
is stored in the browser. You can open theConsole
in the browser, selectApplication
, and find#Cookie
in storageis viewed:
automaticallyAddCookieto the
request headerso that the server can obtain thisCookie, as follows:
username,
id, etc.) Generate a
Cookieand store it in the browser, then every subsequent network request will automatically carry the
Cookie.
Cookieand whether there are valid
usernameand
id# in theCookie
##To determine whether the user has logged in, won't the user's login status be saved?Go back to the Weibo example we mentioned above. According to this process, when the user logs in,
has been saved. At this time, when the user publishes, follows, and comments When we need to log in to use the operation, we can determine in advance whetherCookie
exists. If it exists andCookie
contains the user'sid
, then we can Allow these operations for the user (these operations generally require the user'sid
, which can be obtained fromCookie
). On the contrary, ifCookie
does not exist orCookie
is invalid, then these operations of the user are prohibited.Speaking of this, you may ask:
Cookiecan achieve the effect we want, why should we useSession
?This is because
Cookieis easily forged!, if we know that the information stored in
Cookieisusername
andid
(even if we don’t know, we can also make a request to the network after logging inCookie
is found in the body), then we can manually store a fakeCookie
in the browser without logging in:
Speaking of this, you should be able to understand why
cannot be used alone.
is actually implemented based onCookie
, andSession
is stored in the memory or database of the server.
When the user logs in successfully, the login verification using
Cookie&Session
will perform the following operations:
is generated by the serverSession
andSessionId
;
Session
is generally generated based on the user’s login information, such as user name,id
, etc.
IfSession
is compared to a lock, thenSessionId
is equivalent to the key of the lock.
The server will storeSession
in memory or database;
The server will storeSessionId
is stored in theSet-Cookie
field in the request's response header (response
object) and sent to the client;
After receivingSet-Cookie
, the client will automatically store the value ofSet-Cookie
(that is,SessionId
) intoCookie
;
Every subsequent network request willautomaticallybringCookie
, that is, bring thisSessionId
;
When the server receives a subsequent request, it obtains theCookie
on the request, that is, it obtains theSessionId
, and then passes theSessionId
Query and verify theSessionstored on the
server. If the verification is successful, it means that theSessionId
is valid and the request will be passed. Otherwise, the request will be blocked.
Illustration:

##2️⃣ Cookie&Session defects
Storage issues
In order to save the user's login status, we need to generate and storeSessionfor each logged in user, which will inevitably cause the following problems :
If
- Session
is stored in memory, then when the server restarts, the
Sessionin these memories will be cleared, then all users’ The login status will expire, and when the number of users is large, excessive memory usage will inevitably affect the performance of the server.
If
- Session
is stored in the database, although it can solve the problem of user login status expiration due to server restart, when the number of users is large, the maintenance of this database will also change. relatively difficult.
If the interface called in the front-end page comes from two servers (that is, two sets of databases), in order to achieve
- Session
sharing between the two servers, the
Sessionis usually Stored in a separate database, this makes the entire project more complex and difficult to maintain.

CSRF problem
CSRFis called Cross-site request forgery.Cross-site request forgery, websites that useCookiefor verification will face large or small
CSRFthreats, we use an example of a bank website to introduce CSRF Attack principle:
If a bank'swebsite A's login authentication uses
Cookie&Session, and the
transfer operationis used to run the # on the website ##Api addressis:http://www.grillbankapi.com/?account=AccoutName&amount=1000
##api
Parameters:
accountrepresents the account name,
amountrepresents the transfer amount.
Then, a malicious attacker can place the following code on another
website B
:![Node learning talks about the working principle of Cookie-Session login verification]()
Note:
img
Thenot long ago, the login information has not expired (src
website Aof the tag is the
api addressof the transfer operation of
website A, and the parameter
accountis Ailjx, and
amountis 1000 , that is to say, this
api addressis equivalent to the
apicalled when the account name is Ailjx and transfers 1000.
If a user with the account name Ailjx has just visited
Cookieof
website Aexists and valid).
Then when Ailjx visits this malicious
website B
imgtag will be loaded, and the browser will automatically request the
imgtag The
srcroute is the request
http://www.grillbankapi.com/?account=Ailjx&amount=1000(we record this request as
requestQ), and because
Cookieis stored in the browser and the browser will automatically bring
Cookiewhen sending a request, so
request Qwill automatically carry Ailjx in The
Cookiecertificate on
website A, the result is that this
request Q
will be passed, then Ailjx willlose 1000 funds
.
This kind of malicious URL can take many forms and be hidden in many places on the web page.Additionally, the attacker does not need to control the website where the malicious URL is placed. For example, he can hide this address in forums, blogs, or any other website with user-generated content. This means thatif there are no appropriate defense measures on the server side, users are still at risk of being attacked even if they visit familiar and trusted websites.
As can be seen from the example, the attacker cannot directly obtain the user's account control through CSRF attacks, nor can he directly steal any user information. What they can do istrick the user's browser into running operations on the user's behalf.
These are the problems with usingCookie&Session
for login verification, so how do we solve these problems? This requires introducing the concept ofJWTand usingtoken
for login verification, which we will explain in subsequent articles.
For more node-related knowledge, please visit:nodejs tutorial!
The above is the detailed content of Node learning talks about the working principle of Cookie-Session login verification. For more information, please follow other related articles on the PHP Chinese website!