NodeJs: Authentication Through Facebook Using PassportJs
Posted By : Nisheet Sharma | 28-Mar-2018
NodeJs: Authentication through Facebook using PassportJs
Here we will see, how to add Authentication to your application through Facebook via OAuth using
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:
3. Next, let's install the Facebook Passport Strategy using:
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
where you want Facebook to revert the user to.
So, here we are assuming you have an endpoint /
Another useful option isprofileFields, 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
To view all the possibleprofileFields, you can refer to https://developers.facebook.com/docs/graph-api/reference/v2.5/user
In addition to the
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
3. profile - This is the parameter, that will contain the fetched
4. CB - This is the Callback function, which takes two arguments, first is an error for error cases,
second
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
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);
});
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Nisheet Sharma
Nisheet is a Full Stack Developer (MEAN). He is familiar with C, C++, Java, Html, Css, JavaScript, MySql, MongoDb, AngularJs, NodeJs, ExpressJs.