Node and Passport JS — Facebook Authentication

Sjlouji
The Startup
Published in
4 min readSep 21, 2020
Cover Image

As a user, It’s very often we would have used Facebook accounts to login to a web application. The process would have been so simple. This blog will explain to you how to implement Facebook authentication with Node and Express JS. To implement this, we will be using a third-party library called Passport JS. Passport JS is authentication middleware for Node and Express JS. Passport JS can be used with any Express JS applications. Passport JS provides 500 + strategies.

  1. Initializing a Node JS Project

Initially let’s create a new Node js Project. The below commands create a new folder and then initializes the node to our project.

mkdir facebook_passport
cd facebook_passport/
npm init -y
touch index.js

Now install the required packages.

npm install express cookie-session passport passport-facebook --save

After installing, copy the below code to your index.js file.

index.js

const express = require('express')
const app = express()
app.get('/',(req,res)=>{
res.send('Hello world')
})
app.listen(8000,()=>{
console.log('Serve is up and running at the port 8000')
})

Now start the server using node index.js. Then navigate to http://localhost:8000/. You should see Hello world getting displayed in the browser.

2. Creating OAuth client ID

Before using the passport’s Facebook Authentication strategy, you should have registered your app or web application with Facebook. To do that, follow the steps below.

a. Login to Facebook developers dashboard.

b. Navigate to MyApps page.

https://developers.facebook.com/apps

Creating a new App

c. Hit the Create App button.

d. Now a Model dialog box will open. Choose the type of app you want to create. After choosing, give a name for your app and hit the Create App ID button.

e. Now, a new app would have been created. Navigate to Settings -> Basics.

Facebook OAuth Client ID

f. At the top, you will see the App ID and App secret displayed. Make a note of it.

3. Configuring Facebook OAuth

Now let’s start integrating Facebook Authentication with our project. To do that I am creating a new file named passport.js which holds the credentials that we created from the Facebook developer’s Dashboard.

passport.js

const passport = require('passport');
const FacebookStrategy = require('passport-facebook').Strategy;
passport.serializeUser(function(user, done) {
done(null, user);
});
passport.deserializeUser(function(user, done) {
done(null, user);
});
passport.use(new FacebookStrategy({
clientID: "611015742909469",
clientSecret: "757**********************bed",
callbackURL: "http://localhost:8000/auth/facebook/callback"
},
function(accessToken, refreshToken, profile, done) {
return done(null, profile);
}

));

Copy and paste the below code to your index.js file.

The route /auth/facebook redirects the client to Facebook Login Page.

The route /auth/facebook/callback will act as a callback URL which will be called if Facebook Authentication is Successful.

The route /ath/error will be called if any error has occurred during Facebook Authentication.

index.js

const express = require('express')
const app = express()
const cookieSession = require('cookie-session')
const passport = require('passport');
require('./passport')
app.use(cookieSession({
name: 'facebook-auth-session',
keys: ['key1', 'key2']
}))
app.use(passport.initialize());
app.use(passport.session());
app.get('/',(req,res)=>{
res.send(`Hello world ${req.user.displayName}`)
})
app.get('/auth/error', (req, res) => res.send('Unknown Error'))app.get('/auth/facebook',passport.authenticate('facebook'));app.get('/auth/facebook/callback',passport.authenticate('facebook', { failureRedirect: '/login' }),
function(req, res) {
res.redirect('/');
});
app.listen(8000,()=>{
console.log('Serve is up and running at the port 8000')
})

Now navigate to http://localhost:8000/auth/facebook. You will be redirected to Facebook’s Login page. On logging in to your Facebook account, you will be redirected back to our webpage and you will see your Facebook User name getting displayed on our webpage.

4. Protecting Route and adding a logout view

Now let’s add middleware to find if the user has logged in or not. To do that, I am creating a file named auth.js in the Middleware folder.

Middleware/auth.js

const isLoggedIn = (req, res, next) => {if (req.user) {
next();
} else {
res.status(401).send('Not Logged In');
}
}
module.exports = isLoggedIn

Once done, pass the middleware to the route /. Now navigate to the URL http://localhost:8000/. Automatically you will be redirected to the /auth/facebook route.

Now let’s create a function for logout. Just by calling the function req.logout() you can logout from the Facebook Account.

index.js

const isLoggedIn = require('./Middleware/auth')app.get('/',isLoggedIn,(req,res)=>{
res.send(`Hello world ${req.user.displayName}`)
})
app.get('/logout', (req, res) => {
req.session = null;
req.logout();
res.redirect('/');
})

Just navigate to http://localhost:8000/logout. You will be logged out.

Do visit my previous blog where I have implemented Google OAuth Authentication with Passport JS.

Feel free to contact me for any queries.

Email: sjlouji10@gmail.com

Linkedin: https://www.linkedin.com/in/sjlouji/

Complete code on my GitHub:

Happy coding…

--

--

Sjlouji
The Startup

Software Engineer at @Pando. Developer | Writer. From ABC to the world of code.