using passport for facebook authentication

passport and passport-facebook offers very easy facebook authentication integration into your node app. for the most part, it’s very straightforward, but i got tripped up in a few places.

i’m using krakenjs for my express framework so you have to be a little mindful that some of the express setup stuff has been abstracted away from you. because of that, i was puzzled because i didn’t understand why i couldn’t get access to the passport user object once authenticated.

sessions
passport wants to uses sessions. make sure that you enable the express session middleware and make sure you use the middleware before trying to use passport. order matters here. additionally, if you are using cluster, you can’t use in-memory sessions, you’ll have to use something that is globally accessible by all node processes…something like redis can be used via connect-redis.

passport extends express’ req with the isAuthenticated() method
i initially thought that i had to implement and check whether or not the user is authenticated, but passport handles this for you.

you have to implement passport.serializeUser() and passport.deserializeUser()
passport.serializeUser() is the function that will serialize the user info into the session, typically the user ID. at this point, you have access to the Facebook profile object, so you have information like: facebook user ID, username, displayName, etc.

This function is run once at time of authentication to put the authenticated user into the session.

passport.deserializeUser() is the function that will take the user ID from the session then construct the full information of the user and then make this object available in req.user. this function is run on every request to construct the req.user object so make sure that this code is performant. documentation everywhere says that this is where you would query a database to get user information, but it seems like involving a caching layer here would be advised.

Leave a Reply

Your email address will not be published. Required fields are marked *