简体   繁体   中英

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 passport session functions:

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 get called for every request that needs to be authenticated? Or are they just called once when the session is first created?

2) How do I access the information that is in "user" from other parts of my script?

3) For requests that need to be authenticated, where do I put any additional logic. eg To check if an allowable user idletime value has not been reached.

Thanks (in advance) for your help

1) serializeUser is called when creating a session for the user (when authentication was successful). This is used to store some sort of identifying information (like a unique user-id) about the user in an Express session.

deserializeUser is called for every request, and takes that piece of identifying information from the session to somehow convert it back to a full user record by means of a database query, perhaps, but that's really up to you: instead of just storing the user id you could also store the entire user record in the session, but it depends on the type of user record and the session storage you're using if that's possible (for example, using express.cookieSession would limit the amount of data you can store in a session).

This is what storing the entire user record could look like:

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's stored in the session by serializeUser()
  done(null, user);
});

2) Passport populates req.user which you can use in routes or middleware.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM