代码区项目交易流程

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

Problem courtesy of: user1031947

Solution

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.

Solution courtesy of: robertklep

本文前端(javascript)相关术语:javascript是什么意思 javascript下载 javascript权威指南 javascript基础教程 javascript 正则表达式 javascript设计模式 javascript高级程序设计 精通javascript javascript教程

点击收藏

LAST Build Faster JavaScript Web Apps with Angular Universal, a TransferState Service ... Filtering each object with an equal value in individual arrays NEXT