Home>Article>Web Front-end> Node learning talks about the working principle of Cookie-Session login verification

Node learning talks about the working principle of Cookie-Session login verification

青灯夜游
青灯夜游 forward
2022-11-30 20:52:51 2377browse

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&SessionandJWT. In this section we will first discuss theCookie&SessionThe working principlewill be introduced in detail. In subsequent articles, we will successively introduceJWTand how to useCookie&SessionandJWTto improve what we have learned in the previous sections. The simple user management system built is explained. [Related tutorial recommendations:nodejs video tutorial]

1️⃣ Cookie&Session

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,CookieandSessioncan be introduced to save the user's login status.

This article mainly introduces theworking principle of usingCookie-Sessionfor login verification, aboutCookieandFor a detailed introduction to Session, please refer to this guy’s article:Cookie and Session Detailed Explanation

Why not use Cookie alone?

Cookieis stored in the browser. You can open theConsolein the browser, selectApplication, and find#Cookiein storageis viewed:

Node learning talks about the working principle of Cookie-Session login verification

When the client sends a network request to the server, the browser will

automaticallyAddCookieto therequest headerso that the server can obtain thisCookie, as follows:

Node learning talks about the working principle of Cookie-Session login verification

After knowing this principle, we can think of, if when the user logs in to the system: the client uses part of the user's login information (such as

username,id, etc.) Generate aCookieand store it in the browser, then every subsequent network request will automatically carry theCookie.

Then let the server determine whether the request carries

Cookieand whether there are validusernameandid# 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,

Cookie

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 whetherCookieexists. If it exists andCookiecontains 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, ifCookiedoes not exist orCookieis invalid, then these operations of the user are prohibited.Speaking of this, you may ask:

Since a

Cookiecan achieve the effect we want, why should we useSession?This is because

Cookieis easily forged!, if we know that the information stored inCookieisusernameandid(even if we don’t know, we can also make a request to the network after logging inCookieis found in the body), then we can manually store a fakeCookiein the browser without logging in:

Node learning talks about the working principle of Cookie-Session login verificationSpeaking of this, you should be able to understand why

Cookie

cannot be used alone.

#How is Session combined with Cookie?

Session

is actually implemented based onCookie, andSessionis stored in the memory or database of the server.

When the user logs in successfully, the login verification usingCookie&Sessionwill perform the following operations:

  • is generated by the serverSessionandSessionId;

    Sessionis generally generated based on the user’s login information, such as user name,id, etc.
    IfSessionis compared to a lock, thenSessionIdis equivalent to the key of the lock.

  • The server will storeSessionin memory or database;

  • The server will storeSessionIdis stored in theSet-Cookiefield in the request's response header (responseobject) 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 theCookieon the request, that is, it obtains theSessionId, and then passes theSessionIdQuery and verify theSessionstored on theserver. If the verification is successful, it means that theSessionIdis valid and the request will be passed. Otherwise, the request will be blocked.

Illustration:

Node learning talks about the working principle of Cookie-Session login verification

##2️⃣ Cookie&Session defects

Storage issues

In order to save the user's login status, we need to generate and store

Sessionfor each logged in user, which will inevitably cause the following problems :

    If
  • Sessionis stored in memory, then when the server restarts, theSessionin 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
  • Sessionis 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
  • Sessionsharing between the two servers, theSessionis usually Stored in a separate database, this makes the entire project more complex and difficult to maintain.
    Node learning talks about the working principle of Cookie-Session login verification

CSRF problem

CSRFis called Cross-site request forgery.Cross-site request forgery, websites that useCookiefor verification will face large or smallCSRFthreats, we use an example of a bank website to introduce CSRF Attack principle:

If a bank's

website A's login authentication usesCookie&Session, and thetransfer 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
The

srcof the tag is theapi addressof the transfer operation ofwebsite A, and the parameteraccountis Ailjx, andamountis 1000 , that is to say, thisapi addressis equivalent to theapicalled when the account name is Ailjx and transfers 1000.If a user with the account name Ailjx has just visited

website A
not long ago, the login information has not expired (

Cookieofwebsite Aexists and valid).Then when Ailjx visits this maliciouswebsite B

, the above

imgtag will be loaded, and the browser will automatically request theimgtag Thesrcroute is the requesthttp://www.grillbankapi.com/?account=Ailjx&amount=1000(we record this request asrequestQ), and becauseCookieis stored in the browser and the browser will automatically bringCookiewhen sending a request, sorequest Qwill automatically carry Ailjx in TheCookiecertificate onwebsite A, the result is that thisrequest Qwill 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&Sessionfor login verification, so how do we solve these problems? This requires introducing the concept ofJWTand usingtokenfor 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!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete