A mini-project to practice Passport/Node.js
Create a simple app that shows Facebook Profile information.
You can use the passport-facebook GitHub repo for a guide.
Set up a index.js file and include these npm dependencies:
- express
- express-session
- passport
- passport-facebook
Go over to the Facebook Developer Portal and Add a New App. Call it whatever you'd like.
Now let's put in the code necessary to get our authentication working:
-
Create your express app, have it listen to a port that works for you
-
Require passport and the passport FacebookStrategy
const passport = require('passport')
const FacebookStrategy = require('passport-facebook').Strategy
-
Include the session middleware
app.use(session({ secret: 'some-random-string' }))
-
Include the passport.initialize middleware
app.use(passport.initialize())
-
Include the passport.session middleware
app.use(passport.session())
-
Define the FacebookStrategy
passport.use(new FacebookStrategy({ clientID: '<your_client_id>', clientSecret: '<your_client_secret>', callbackURL: 'http://localhost:3000/auth/facebook/callback' }, function(token, refreshToken, profile, done) { return done(null, profile); }));
Create two routes that will handle your Facebook auth.
This route simply implements the passport.authenticate method, passing 'facebook' as the parameter.
This route needs to pass the passport.authenticate method again, except we also need to pass in an object that passes the successRedirect and failureRedirect paths.
Since you won't be doing anything further than just passing objects to/from passport and the session, we just need bare bones methods here:
passport.serializeUser(function(user, done) {
done(null, user);
});
passport.deserializeUser(function(obj, done) {
done(null, obj);
});
Now we're going to create an endpoint that returns the current logged in user's Facebook profile data.
Create this route in your index.js that returns the user's Facebook profile data. The data is stored in req.user
if you've set everything up correctly. Return a JSON representation of this data at the /me
endpoint.
Use Postman or the browser to verify that you can in fact get the JSON data from the /me
endpoint.
© DevMountain LLC, 2016. Unauthorized use and/or duplication of this material without express and written permission from DevMountain, LLC is strictly prohibited. Excerpts and links may be used, provided that full and clear credit is given to DevMountain with appropriate and specific direction to the original content.