NodeJs: Authentication Through Facebook Using PassportJs

Posted By : Nisheet Sharma | 28-Mar-2018

NodeJs: Authentication through Facebook using PassportJs

 

 

PassportJs is a middleware, that can be used for implementing various types of Authentication processes.

 

Here we will see, how to add Authentication to your application through Facebook via OAuth using PassportJs.

Steps to Implement:

1. Register your application on Facebook
Go to https://developers.facebook.com/ and create a Facebook Developer account if you don't have one,
and through it register the application in which you are going to add the Facebook Authentication process.
Once, you have registered the application, Facebook will issue an App ID and an App Secret
for the same.

2. Now, install the Passport module using:
npm install passport

3. Next, let's install the Facebook Passport Strategy using:
npm install passport-facebook

 

Once, we have all the dependencies installed, we'll start configuring the Facebook Authentication Process,
to suit our application's needs, as follows.

 

Let's create a new File, that'll configure and return a new Facebook PassportJs Strategy.

First, we'll fetch the modules passport and passport-facebook into our js file, as follows.

        //File: FacebookPassportStrategy.js

        const passportjs = require('passport');
        const FacebookPassportStrategy = require('passport-facebook').Strategy;
    

Now, let's configure the Strategy to suit our needs.

You'll need the App Id and App Secret you got from Facebook Developer Account.

        var facebookOptions = {
            clientID: "App Id you get from Facebook Developer Account here"         //Required
            clientSecret: "App Secret you get from Facebook Developer Account here" //Required
            callbackURL: "http://127.0.0.1:8080/oauth/fb/callback",                 //Required
            profileFields: ['id', 'displayName', 'email']                           //Optional
          };
    

The callbackURL in the above options will be the API endpoint of your application,
where you want Facebook to revert the user to.
So, here we are assuming you have an endpoint /
oauth/fb/callback, that will serve as the redirect URL.
Another useful option is
profileFields, this is to inform Facebook, which fields of the User's Facebook Profile,
you want to fetch into your application. So, when the user authorizes the use his/her data from Facebook, the permissions section,
will mention the
above mentioned fields.
To view all the possible
profileFields, you can refer to https://developers.facebook.com/docs/graph-api/reference/v2.5/user

In addition to the facebookOptions, we'll need a callback function, that will register/login users in our application,
once facebook has authorized them.
It should have the following arguments:
1. accessToken - This is the OAuth token generated by Facebook for the User.
2. refreshToken - This is the Refresh token, that can be used to renew the
Oauth token via Facebook
3. profile - This is the parameter, that will contain the fetched
profileFields, we mentioned earlier.
4. CB - This is the Callback function, which takes two arguments, first is an error for error cases,
second is
user, for passing user's object, if the user is verified/registered successfully.

        var onAuthentication = (accessToken, refreshToken, profile, cb) => {
            
            //Assume we have a User model in our application that stores all the user's data.
            User.findOne({ oauthId: profile.id },
                function (err, userObj) {
                    
                    if (err) { 
                        //If we encounter an error, signal that to passport using done(err)
                        return cb(err); 
                    }
                    if (!userObj) {
                        // If the user doesn't exist create one
                        User.create({
                            oauthId: profile.id,
                            name: profile.displayName,
                            email: profile.email
                        }, (err, newUser) {
                            if(err) return cb(err);
                            //If user obj is successfully created pass it to the callback.
                            return cb(null, newUser);
                        });
                    }
                    else {
                        // If user already exists in our database, pass their details forward.
                        return cb(null, userObj);
                    }
                }
            );
        };
    

Once, the configuration part is complete, create new Facebook Authentication Strategy, using the passport-facebook module.
As shown below:

        var facebookAuthenticationStrategy = new FacebookPassportStrategy(facebookOptions, onAuthentication);
    

Finally, signal to PassportJs module to use our configured Facebook Authentication Strategy.

        passportjs.use(facebookAuthenticationStrategy);
    

Now, let's define our oauth routes.
First, the API endpoint, we'll use to start the facebook authentication process.

          app.get('/oauth/fb',
          passportjs.authenticate('facebook'));
    


Secondly, the API endpoint, we'll use as facebook's callback URL, the one we passed as facebookOptions while configuring.

          app.get('/oauth/fb/callback',
          passportjs.authenticate('facebook', { failureRedirect: '/oauth/failure' }),
            function(req, res) {
              // The user's details will be appended to the req by PassportJs
              // So, you use it here.
              doSomethingAndRedirectUserToWelcomePage(req.user);
            });
    
 

 

About Author

Author Image
Nisheet Sharma

Nisheet is a Full Stack Developer (MEAN). He is familiar with C, C++, Java, Html, Css, JavaScript, MySql, MongoDb, AngularJs, NodeJs, ExpressJs.

Request for Proposal

Name is required

Comment is required

Sending message..