Github Authentication using Nodejs

    Jun 10, 2016       by Pankaj Kumar
github-authentication-nodejs.jpg

Welcome to Github Authentication, Since making user registration and login fast and easy is an important part of any new application. Fet time back, registration forms were mendatory which mostly users didnot like much, Because of that, alot of web application lost users. And other issue was also with login forms where use had to enter their usernames/emails and passwords. Often users forget their password since its not possible to remember so many passwords and again if login is needful then long step of password recovery. For skipping such issues at the current age users likes to login with third party like google+, facebook, github etc.

So lets start this tutorial where  I am going to explain login with github step by step, In this demo I am not connecting it to any database. So for now we have a single file server.js  where we will perform each and every task related to this tutorial. Lets have a look.

 

 
let express = require('express'),
    app = express(),
    passport = require('passport'),
    session = require('express-session');
let GithubStrategy = require('passport-github').Strategy;
 
/***************************************************************
 *********** Github Configuration setup...
 ***************************************************************/
 
passport.use(new GithubStrategy({
    clientID: " APP CLIENT ID",
    clientSecret: "APP CLIENT SECRET",
    callbackURL: "http://localhost:3000/auth/github/callback"
  },
  function(accessToken, refreshToken, profile, done) {
    // we will just use the profile object returned by GitHub
    return done(null, profile);
  }
));
 
// Express and Passport Session
app.use(session({secret: "jsonworldbestplaformforjsframeworks"}));
app.use(passport.initialize());
app.use(passport.session());
 
passport.serializeUser(function(user, done) {
    // placeholder for custom user serialization
    done(null, user);
});
 
passport.deserializeUser(function(user, done) {
    // placeholder for custom user deserialization.
    // maybe you are getoing to get the user from mongo by id?
    
    done(null, user); // null is for errors
});
 
// we will call this to start the GitHub Login process
app.get('/auth/github', passport.authenticate('github'));
 
// GitHub will call this URL
app.get('/auth/github/callback',
  passport.authenticate('github', { failureRedirect: '/' }),
  function(req, res) {
      res.redirect('/');
  });
 
app.get('/', function (req, res) {
    var html = "<ul>
      <li><a href='/auth/github'>GitHub</a></li>
      <li><a href='/logout'>logout</a></li>
    </ul>";
 
    // data fetched from github server
    if (req.isAuthenticated()) {
      html += "<p>authenticated as user:</p>"
      html += "<pre>" + JSON.stringify(req.user, null, 4) + "</pre>";
    }
 
    res.send(html);
});
 
app.get('/logout', function(req, res){
    req.logout();
    res.redirect('/');
});
 
// Simple route middleware to ensure user is authenticated.
//  Use this route middleware on any resource that needs to be protected.  If
//  the request is authenticated (typically via a persistent login session),
//  the request will proceed.  Otherwise, the user will be redirected to the login page.
 
function ensureAuthenticated(req, res, next) {
    if (req.isAuthenticated()) { return next(); }
    res.redirect('/')
}
 
app.get('/protected', ensureAuthenticated, function(req, res) {
    res.send("acess granted");
});
 
app.listen(3000, function () {
    console.log('App listening at port: 3000');
});
 

 

In the above file, we have included required package needed for the app. Then we have set the configuration needed for github authentication, After that set the express and passport session. Below that we have two urls one is for first page of the app and second url is to receive the callback from the github and at last we have served that data into our page using html. So after creating this file download package.json file from the zip code available and run npm install and type node server.js after opening terminal. If still facing any issue download the working zipped code from here and then simply run npm install and proceed.

 

Pretty cool! Finally, our task completes here.

That’s all for now. Thank you for reading and I hope this post will be very helpful.

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.


WHAT'S NEW

Find other similar Articles here: