Instagram
youtube
Facebook
Twitter

LinkedIn Authentication

LinkedIn Authentication

  • In this tutorial, we will code LinkedIn authentication using ExpressJs and passport.js

To start, Firstly register on your LinkedIn development site and begin with the following steps:

  • Go to the LinkedIn Developer page: LinkedIn.
  • Create a new App and call it whatever you want to. 

  • Fill in the following details, accepts the terms and condition, and click on Create app.

  • Now go to auth and get the clientID and clientsecret and update the Redirect URL.

  • Now let's move to the code part. here is an application file structure.

  • Install passport and other modules in the project by the following command:
npm install passport passport-linkedin-oauth2, express, express-session,ejs
  • For frontend part, views\pages\index.ejs and views\pages\profile.ejs

In index.ejs

<!doctype html>
<html>

<head>
  <title>Linkedin  Authentication</title>
  <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
  <link rel="stylesheet" type="text/css"
    href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.5/css/materialize.min.css">
  <style>
    .linkedin {
      background-color: #0073b1 !important;
      color: #fff !important;
    }
    .fa-linkedin-f:before,
    .fa-linkedin:before {
      content: "\f0e1";
    }
  </style>
</head>

<body>
 
  <div class="section no-pad-bot" id="index-banner">
    <div class="container">
      <br><br>
      <div class="row center">
        <div class="col s6 offset-s3">
          <div class="card">
            <div class="card-content">
              <span class="card-title">Linkedin Login</span>
            </div>
            <div class="card-action">
              <a href="/auth/linkedin" class="waves-effect waves-light btn social linkedin">
                <i class="fa fa-linkedin"></i> Sign in with Linkedin
              </a>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</body>

</html>

In profile.ejs

<!doctype html>
<html>

<head>  
  <title>LinkedIn Authentication</title>
  <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
  <link rel="stylesheet" type="text/css"
    href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.5/css/materialize.min.css">
  <style>
    .card:hover {
      box-shadow: 0 10px 20px rgba(0, 0, 0, 0.19), 0 6px 6px rgba(0, 0, 0, 0.23);
      margin-bottom: 54px;
    }
  </style>
</head>

<body>
  <nav class="light-blue lighten-1" role="navigation">
    <div class="nav-wrapper container">
      <a href="/logout" class="right">Logout</a>
    </div>
  </nav>
  <div class="section no-pad-bot" id="index-banner">
    <div class="container">
      <br><br>
      <div class="row center">
        <div class="col s12">
          <div class="card">
            <div class="card-content blue lighten-3">
              <span class="card-title white-text"><strong><i class="large material-icons">person</i>
                </strong></span>
            </div>
            <div class="card-action">
              <h5><b><%= user.displayName %></b></h5>
              <p><strong>Linkedin id</strong>: <%= user.id %></p>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</body>

</html>

Now moving to the server part

  • Now for routes In routes.js
const passport = require('passport');
const express = require('express');
var router = express.Router();

router.get('/', function (req, res) {
  res.render('pages/index.ejs'); // load the index.ejs file
});

router.get('/profile', isLoggedIn, function (req, res) {
  res.render('pages/profile.ejs', {
    user: req.user // get the user out of session and pass to template
  });
});

router.get('/auth/linkedin', passport.authenticate('linkedin', {
  scope: ['r_emailaddress', 'r_liteprofile'],
}));

router.get('/auth/linkedin/callback',
  passport.authenticate('linkedin', {
    successRedirect: '/profile',
    failureRedirect: '/login'
  }));

router.get('/logout', function (req, res) {
    req.logout(function(err) {
        if (err) { return next(err); }
        res.redirect('/');
      });
});


function isLoggedIn(req, res, next) {
  if (req.isAuthenticated())
    return next();
  res.redirect('/');
}

module.exports = router;
  • clientID, clientsecret, and callback URL are mentioned in config.js
module.exports = {
    'linkedinAuth': {
        'clientID': 'YOUR_CLIENT_ID',
        'clientSecret': 'YOUR_CLIENT_SECRET', // your App Secret
      'callbackURL': 'http://localhost:3000/auth/linkedin/callback'
    }
  }
  • Lastly, for the server there we use passport and express to authenticate, In server.js:
const express = require('express');
const app = express();
const session = require('express-session');
const passport = require('passport');
const LinkedInStrategy = require('passport-linkedin-oauth2').Strategy;
const routes = require('./routes.js');
const config = require('./config')

app.set('view engine', 'ejs');

app.use(session({
  resave: false,
  saveUninitialized: true,
  secret: 'SECRET'
}));

app.use(passport.initialize());
app.use(passport.session());

passport.serializeUser(function (user, cb) {
  cb(null, user);
});

passport.deserializeUser(function (obj, cb) {
  cb(null, obj);
});

passport.use(new LinkedInStrategy({
  clientID: config.linkedinAuth.clientID,
  clientSecret: config.linkedinAuth.clientSecret,
  callbackURL: config.linkedinAuth.callbackURL,
  scope: ['r_emailaddress', 'r_liteprofile'],
}, function (token, tokenSecret, profile, done) {
  return done(null, profile);
}
));

app.use('/', routes);

const port = 3000;

app.listen(port, () => {
  console.log('App listening on port ' + port);
});
npm start

 

 

Thus, LinkedIn authentication can be added to any website or app using Expressjs and passport.js.