When is the passport serialization and deserialization method called? What does he ask exactly?

We have two types of users, administrators and general users.

passport.serializeUser(function(user, done) { console.log('Sear'); done(null, user.id); }); passport.deserializeUser(function(id, done) { console.log(id); console.log("Deser"); User.findById(id, function(err, user) { if(err) done(err); if(user){ done(null, user); }else{ vendorUser.findById(id, function(err, user){ if(err) done(err); done(null,user); }); } }); }); 

Console.log is often displayed (even for a single API request) with text

Deser

What do both functions do? A detailed answer is welcome. TIA.

+8
authentication mongoose express
source share
2 answers

Serialization and deserialization are an important concept. Serializing an object means converting its state into a byte stream so that the byte stream can be returned back to the copy of the object.

In a typical web application, the credentials used to authenticate the user will only be transmitted during the login request. If authentication succeeds, the session will be created and maintained through a set of cookies in the user’s browser.

Each subsequent request will not contain credentials, but rather a unique cookie that identifies the session. To support login sessions, Passport will serialize and deserialize user instances in and out of the session.

In the code you wrote for the session, only the user ID is serialized. Upon receipt of subsequent requests, this identifier is used to search for the user who will be restored before req.user .

To give developers freedom for the user depending on which database they want, no matter what data they want to serialize, they can do it their own way, the logic of serialization and deserialization remains for us.

+19
source share

serializeUser is a method that is called in a login request (during authentication), and if the login is successfully completed, it decides what user information should be stored in the session, and the cookie is sent to the browser to save the session in the same way.

 // Only during the authentication to specify what user information should be stored in the session. passport.serializeUser(function (user, done) { console.log("Serializer : ", user) done(null, user.id); }); 

The above snippet will save the user.id field in the session and cookie.

deserializeUser is a method that is called for the entire subsequent request and called by the passport.session middleware. This allows us to download additional user information for each request. This custom object is attached to the request as req.user, which makes it available when processing requests.

Here is an article that explains that the flow is very good

+2
source share

All Articles