


Node learning talks about the working principle of Cookie-Session login verification
At present, most systems are indispensable for the Login verification function. 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 status after login.
There are two main ways to implement login verification: Cookie&Session
and JWT
. In this section we will first discuss the Cookie&Session
The working principle will be introduced in detail. In subsequent articles, we will successively introduce JWT
and how to use Cookie&Session
and JWT
to 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 status after login.
At this time, Cookie
and Session
can be introduced to save the user's login status.
This article mainly introduces the
working principle of using
Cookie-Session for login verification, aboutCookie
andFor a detailed introduction to Session
, please refer to this guy’s article: Cookie and Session Detailed Explanation
Why not use Cookie alone?
Cookie
is stored in the browser. You can open the Console
in the browser, select Application
, and find#Cookie
in storage is viewed:
automatically Add Cookie to the
request header so that the server can obtain this Cookie, as follows:
username,
id, etc.) Generate a
Cookie and store it in the browser, then every subsequent network request will automatically carry the
Cookie.
Cookie and whether there are valid
username and
id# in the Cookie
##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 whether Cookie
exists. If it exists and Cookie
contains the user's id
, then we can Allow these operations for the user (these operations generally require the user's id
, which can be obtained from Cookie
). On the contrary, if Cookie
does not exist or Cookie
is invalid, then these operations of the user are prohibited. Speaking of this, you may ask:
Cookie can achieve the effect we want, why should we use Session
? This is because
Cookie is easily forged! , if we know that the information stored in
Cookie is username
and id
(even if we don’t know, we can also make a request to the network after logging in Cookie
is found in the body), then we can manually store a fake Cookie
in the browser without logging in:
Speaking of this, you should be able to understand why
cannot be used alone.
#How is Session combined with Cookie?
Session is actually implemented based on When the user logs in successfully, the login verification using is generated by the server The server will store The server will store After receiving Every subsequent network request will automatically bring When the server receives a subsequent request, it obtains the Illustration: Session CSRF is called Cross-site request forgery. Cross-site request forgery, websites that use Cookie website A accountCookie
, and Session
is stored in the memory or database of the server. Cookie&Session
will perform the following operations:
Session
and SessionId
; Session
is generally generated based on the user’s login information, such as user name, id
, etc.
If Session
is compared to a lock, then SessionId
is equivalent to the key of the lock. Session
in memory or database; SessionId
is stored in the Set-Cookie
field in the request's response header (response
object) and sent to the client; Set-Cookie
, the client will automatically store the value of Set-Cookie
(that is, SessionId
) into Cookie
; Cookie
, that is, bring this SessionId
;Cookie
on the request, that is, it obtains the SessionId
, and then passes the SessionId
Query and verify the Session stored on the
server. If the verification is successful, it means that the SessionId
is valid and the request will be passed. Otherwise, the request will be blocked.
##2️⃣ Cookie&Session defects
Storage issues
In order to save the user's login status, we need to generate and store for each logged in user, which will inevitably cause the following problems :
If
is stored in memory, then when the server restarts, the
Session in 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.
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.
sharing between the two servers, the
Session is usually Stored in a separate database, this makes the entire project more complex and difficult to maintain.
CSRF problem
for verification will face large or small
CSRF threats, we use an example of a bank website to introduce CSRF Attack principle:
's login authentication uses
Cookie&Session, and the
transfer operation is used to run the # on the website ##Api address is: http://www.grillbankapi.com/?account=AccoutName&amount=1000
Parameters:
:
represents the account name,
amount represents the transfer amount.
Then, a malicious attacker can place the following code on another
<img src="/static/imghwm/default1.png" data-src="http://www.grillbankapi.com/?account=Ailjx&amount=1000" class="lazy" alt="Node learning talks about the working principle of Cookie-Session login verification" >
Note:
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
Cookie of
website A exists and valid).
Then when Ailjx visits this malicious
website B
img tag will be loaded, and the browser will automatically request the
img tag The
src route is the request
http://www.grillbankapi.com/?account=Ailjx&amount=1000 (we record this request as
requestQ ), and because
Cookie is stored in the browser and the browser will automatically bring
Cookie when sending a request, so
request Q will automatically carry Ailjx in The
Cookie certificate on
website A, the result is that this
request Q
will be passed , then Ailjx will lose 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 that if 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 is trick the user's browser into running operations on the user's behalf.
These are the problems with using Cookie&Session
for login verification, so how do we solve these problems? This requires introducing the concept of JWT and using token
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!

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 Chinese version
Chinese version, very easy to use

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver Mac version
Visual web development tools

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.