Login with Linkedin in nodejs application

sample appliction image

In this article, We will create a demo to log in with Linkedin in our Nodejs application. Since login with social is almost available at the maximum number of mobile or web application. Also, I have already covered the login with twitter, facebook and facebook over this platform earlier.

 

What is Passport?

Passport is a library that provides a mechanism for easily setting up an authentication/registration system with support for several frameworks and auth providers. In this tutorial, we’ll demonstrate in detail how to integrate this library into a Node.JS/Express 4 application to provide user authentication through LinkedIn using OAuth 2.0.

 

What is OAuth 2.0?

OAUTH 2.0 is the successor of the OAuth protocol (an open standard for authorization), which enables third-party applications, such as the one we’ll be building, access to an HTTP service without having to share secure credentials.

 

So let's proceed to create the app step by step.

Step 1: Create Client ID and Secret

Follow the link to create an app over Linkedin for getting a client id and secret Click here. Then login into your LinkedIn account. After login, you will see a  menu at the right top named My Apps. Once on clicking on that menu a page will show like below

login with linkedin

On the above page click on Create Application button, a form will open after clicking like below:

 

Fill all the fields and then click on the submit button, After successful submit of form a new page will open like below having newly generated client id and secret with the option to set redirect URL

Login with linkedin3

Now Client ID and the secret has been generated. Click on update button after filling the redirect URL.

 

Step 2: Set passport and node side code

Node let's configure the task at node.js end. So let's see our server.js file, which is having all the major task at node.js end. 

 

 
var express = require('express'),
util = require('util'),
session = require('express-session'),
cookieParser = require('cookie-parser'),
bodyParser = require('body-parser'),
router = express.Router(),
app = express();
// package related to passport and oauth2.0
var passport = require('passport');
var LinkedInStrategy = require('passport-linkedin-oauth2').Strategy;
 
app.use(cookieParser());
app.use(bodyParser.urlencoded({ extended: false }));
 
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(express.static(__dirname + '/public'));
 
// session related task & passport intiallization...
app.use(session({ secret: 'jsonworldplaceforjsdemos'}));
app.use(passport.initialize());
app.use(passport.session());
 
// Passport session setup, Passport needs to serialize and deserialize user instances from a session store to support login sessions. 
passport.serializeUser(function(user, done) {
done(null, user);
});
 
passport.deserializeUser(function(obj, done) {
done(null, obj);
});
 
 
passport.use(new LinkedInStrategy({
clientID: 'ENTER_CLIENT_ID',
clientSecret: 'ENTER CLIENT SECRET',
callbackURL: "http://localhost:3000/callback/",
scope: ['r_emailaddress', 'r_basicprofile'],
}, function(accessToken, refreshToken, profile, done) {
// asynchronous verification, for effect...
process.nextTick(function () {
// To keep the example simple, the user's LinkedIn profile is returned to
// represent the logged-in user. In a typical application, you would want
// to associate the LinkedIn account with a user record in your database,
// and return that user instead.
return done(null, profile);
});
}));
 
// Using FacebookStrategy within Passport here to perform the actual task...
/* GOOGLE ROUTER */
app.get('/linkedin',
passport.authenticate('linkedin'));
// callback method which linkedin will hit after successfull login of user
app.get('/callback/',
passport.authenticate('linkedin', { failureRedirect: '/login' }),
function(req, res) {
res.redirect('/');
});
// method to load index.ejs file on base path
app.get('/', function(req, res){
res.render('index', { user: req.user });
});
 
function ensureAuthenticated(req, res, next) {
if (req.isAuthenticated()) { return next(); }
res.redirect('/login')
}
// Method to logout
app.get('/logout', function(req, res){
req.logout();
res.redirect('/');
});
 
app.listen(3000,function(){
console.log('server running on port:3000')
});
 

 

In the above file, At the top, we have included the needed node.js package with passport related packages. And below that, we have configured passport. And at the bottom, we have defined the routing and needed methods in our app.

 

Now lets come to the view part, have a look our ejs file. Let's have a look on index.ejs file.

 

 
<% if (!user) { %>
<div>
    <h2 style="font-size:40px;">Please log in.</h2>
    <a href="/linkedin"><img src="login-with-linkedin.png" width="171" height="34"></a>
    </div>
<% } else { %>
 
    <div>
            <h2>Hello, <%= user.displayName %>.</h2>
        <p >
                <a style="padding-right:10px;" href="/">Home</a> |
                <a style="padding-right:10px;" href="/logout">Log Out</a>
            </p>
    
                <h3>My Profile</h3>
                            <p>ID: <%= user.id %></p>
                            <p>Username: <%= user.username %></p>
                            <p>Name :<%= user.displayName %></p>
            
            </div>
 
<% } %>
 

 

 

In the above file, we are managing log in button or profile data after login.  Follow the steps provided in the read.me file and run the app with URL http://localhost:3000.

 

That’s all for now. Thank you for reading and I hope this post will be very helpful for implementation of login with LinkedIn in node.js application.

Let me know your thoughts over the email demo.jsonworld@gmail.com. I would love to hear them and If you like this article, share with your friends.

 

You can download complete code from here. Download Code