Passport for authentication in Node JS

I am considering using the Passport library ( http://passportjs.org/ ) for authentication in a Node project.

I am confused by the following functions of the passport session:

passport.serializeUser(function( user, done ) { done( null, user.id ); }); passport.deserializeUser(function( id, done ) { user.get( id, function ( err, user ) { done( err, user ); }); }); 

I am wondering:

1) Do these calls get for every request that needs to be authenticated? Or are they just called once when the session is first created?

2) How to access the information in the "user" from other parts of my script?

3) For requests that need authentication, where I can add additional logic. for example, to verify that a valid user idleime has not been reached.

Thank you (in advance) for your help.

+4
source share
1 answer

1) serializeUser is called when creating a session for the user (when authentication was successful). This is used to store any identifying information (for example, a unique user identifier) โ€‹โ€‹about the user in an Express session.

deserializeUser is called for each request and takes this piece of identifying information from the session to somehow convert it back to a full user record using a database query, perhaps, but it really depends on you: instead of just storing the user ID, you can also save all user record in a session, but it depends on the type of user account and session you are using, if it is possible (for example, the use of express.cookieSession limited to the amount of data you can save in the session).

This is what might look like a record of the entire user record:

 passport.serializeUser(function(user, done) { // Here, 'user' is the result of the function called by 'new LocalStrategy()'; when // you call done() below, that result will be stored in the session. done(null, user); }); passport.deserializeUser(function(user, done) { // Here, 'user' is what stored in the session by serializeUser() done(null, user); }); 

2) The passport fills out req.user , which you can use in routes or middleware.

3) You can create middleware to implement such checks. This could be a good starting point.

+3
source

Source: https://habr.com/ru/post/1469311/


All Articles