How to create social login in Nodejs
Posted By : Mayank Tyagi | 30-Apr-2015
Integrating social logins in the website:- To integrate social login in our node.js application we need to install passport in our package.json file of project to inject the dependency of passport .Then we need to use some method of passport in our app.js file .
passport.serializeUser(function (user, done) { done(null, user); }); passport.deserializeUser(function (user, done) { done(null, user); });
To install passport inject the following in package.json:- "passport": "~0.2.1" include the following file in your app.js:- var passport = require('passport');
Step 1:- Install facebook dependency in package.json by using "passport-facebook": "~2.0.0" in the file.
Step 2:- Create a develepor account on facebook.
Step 3:- Include the file for facebook authorization in your app.js var FacebookStrategy = require('passport-facebook').Strategy;
Step 4:- Create a json in your config file:-
var facebookAuth = { 'appID' : '-------', // your App ID 'appSecret' : '----------------', // your App Secret 'callbackUrl' : 'http://localhost:3000/api/v1/auth/facebook/callback' }
Note:- generate your appId and appsecret from the facebook developer account and set your callback url in the account also.
Step 5:- Create router for your request:-
router.get('/api/v1/auth/facebook', passport.authenticate('facebook', { scope: ['email'] }), function (req, res) {});
Step 6 :- Now start code for facebook login .
passport.use(new FacebookStrategy({ clientID : configurationHolder.config.facebookAuth.appID, clientSecret : configurationHolder.config.facebookAuth.appSecret, callbackURL : configurationHolder.config.facebookAuth.callbackUrl }, function (accessToken, refreshToken, profile, done) { domain.User.findOne({$or:[{ facebookAuthId: profile.id},{email:profile._json.email} ]}, function(err, user){ if(err){ console.log(err); } else if((!err && user != null) ){ if(user.email ==profile._json.email){ domain.User.update({email:profile._json.email},{facebookAuthId : profile.id},function(err,user){ if(err){console.log(err)} else{done(null, profile._json);} }); } else{done(null, profile._json)} } else{ var newUser = new domain.User({ facebookAuthId : profile.id, firstName : profile.name.givenName, lastName : profile.name.familyName, email : profile._json.email, role : "ROLE_USER", password:"checkitout" }); newUser.save(function(err){ if(err){console.log(err)} else{done(null, newUser);} }); } }); } ));
Step7 :-
router.get('/api/v1/auth/facebook', passport.authenticate('facebook', { scope: ['email'] }), function (req, res) {}); router.get('/api/v1/auth/facebook/callback', passport.authenticate('facebook', { failureRedirect: '/' }), function (req, res) { res.redirect(“yoursiteurl”); });
-> Creating Social login for google step1:- install google dependency in package.json by using "passport-google": "latest" in the file. Step2:-create a develepor account on google. Step3:- include the file for google authorization in your app.js var GoogleStrategy = require('passport-google-oauth').OAuth2Strategy; step4:-create a json in your config file:-
var googleAuth = { 'clientID' : 'your client id', 'clientSecret' : 'your client secret', 'callbackURL' : 'http://localhost:3000/api/v1/google/callback' }
Note:-generate your appId and appsecret from the google developer account and set your callback url in the account also. step5:- create router for your request:-
router.get('/api/v1/auth/google', passport.authenticate('google', { scope: ['email'] }), function (req, res) {});
step6:- now start code for google login
passport.use(new GoogleStrategy({ clientID : configurationHolder.config.googleAuth.clientID, clientSecret : configurationHolder.config.googleAuth.clientSecret, callbackURL : configurationHolder.config.googleAuth.callbackURL }, function (accessToken, refreshToken, profile, done) { domain.User.findOne({$or:[{googleAuthId: profile.id},{email:profile._json.email} ]}, function(err, user){ if(err){ console.log(err); } else if((!err && user != null)){ if(user.email == profile._json.email){ domain.User.update({email:profile._json.email},{googleAuthId : profile.id},function(err,user){ if(err){console.log(err)} else{done(null, profile._json);} }); } else{done(null, profile._json);} } else{ var newUser = new domain.User({ googleAuthId : profile.id, firstName : profile.name.givenName, lastName : profile.name.familyName, email : profile._json.email, role : "ROLE_USER", password:"checkitout" }); newUser.save(function(err){ if(err){console.log(err)} else{done(null, newUser);} }); } }); } ));
step7:-
router.get('/api/v1/auth/google', passport.authenticate('google', { scope: ['email'] }), function (req, res) {}); router.get('/api/v1/auth/google/callback', passport.authenticate('google', { failureRedirect: '/' }), function (req, res) { res.redirect(“yoursiteurl”); });
-> Creating Social login for linkedin step1:- install linkedin dependency in package.json by using "passport-linkedin-oauth2":"latest" in the file. Step2:-create a develepor account on linkedin . Step3:- include the file for linkedin authorization in your app.js var LinkedinStrategy = require('passport-linkedin-oauth2').Strategy; step4:-create a json in your config file:-
var linkedinAuth = { 'consumerKey': 'consumer key', 'consumerSecret': 'consumer secret', 'callbackURL': 'http://localhost:3000/api/v1/linkedin/callback' }
Note:-generate your consumer key and consumer secret from the linked developer account and set your callback url in the account for oauth2url. step5:- create router for your request:-
router.get('/api/v1/auth/linkedin', passport.authenticate('linkedin', { }), function (req, res) {});
step6:-now start code for linkedin login
router.get('/api/v1/linkedin/callback', passport.authenticate('linkedin', { failureRedirect: '/' }), function (req, res) { res.redirect(“your site url”) });
passport.use(new LinkedinStrategy({ clientID : configurationHolder.config.linkedinAuth.consumerKey, clientSecret : configurationHolder.config.linkedinAuth.consumerSecret, callbackURL : configurationHolder.config.linkedinAuth.callbackURL, scope: ['r_emailaddress', 'r_basicprofile'], state: true }, function (accessToken, refreshToken, profile, done) { domain.User.findOne({$or:[{linkedinAuth: profile.id},{email:profile._json.email} ]}, function(err, user){ if(err){ console.log(err); } else if((!err && user != null)){ if(user.email == profile.emails[0].value){ domain.User.update({email:profile.emails[0].value},{linkedinAuth : profile.id},function(err,user){ if(err){console.log(err)} else{done(null, profile._json);} }); } else{done(null, profile._json);} } else{ var newUser = new domain.User({ linkedinAuth : profile.id, firstName : profile.name.givenName, lastName : profile.name.familyName, email : profile.emails[0].value, role : "ROLE_USER", password:"checkitout" }); newUser.save(function(err){ if(err){console.log(err)} else{ done(null, newUser);} }); } }); } ));
step7:-
router.get('/api/v1/linkedin/callback', passport.authenticate('linkedin', { failureRedirect: '/' }), function (req, res) { res.redirect(“your site url”) });
Hope you find this blog helpful.
Thanks and regards,
Mayank Tyagi.
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
Mayank Tyagi
Mayank is a bright Web Developer with expertise in Java language.