Heroku Authentication with PassportJS for Node Applications

In this article we will be implementing authentication via Heroku in a Node.js web application. Fo...

In this article we will be implementing authentication via Heroku in a Node.js web application. For this we'll be using Passport, an authentication middleware for Node.js for heroku. Since passport provides multiple flavors for varied applications, we will use passport-heroku .




Express Web Apps

Install Node.js first on your machine, You will also require Express, a framework for building web application on Node.js.  Lets being by install following command in your terminal

$ npm install -g express


Generate project scaffold, by using 

$ express Visa  // you can name your application to any name you like


You will see project scaffold code, generated here

create : Visa
create : Visa/package.json
create : Visa/app.js
create : Visa/public
create : Visa/public/images
create : Visa/public/stylesheets
create : Visa/public/stylesheets/style.css
create : Visa/routes
create : Visa/routes/index.js
create : Visa/routes/user.js
create : Visa/views
create : Visa/views/layout.jade
create : Visa/views/index.jade
create : Visa/public/javascripts

Now lets install package listed in configuration You can verify your application running at http://localhos:3000


$ npm install  and $ node app.js 




Implementing Heroku Authentication

Let us begin by installing passportjs package for heroku

$ npm install passport

Once package is downloaded then lets design auth.html, I used materializecss, for implementing this   a better layout.



We want our default route to serve this HTML page. In app.js there is already a route for /. Modify that route to serve this file as shown in the following code sample. Once this is done, restart the Node server and refresh your browser, and you should see this page.


app.get('/', function(req, res, next) {
  res.sendfile('./html/auth.html');
});


Now lets register a Heroku Application first, lets click on top right icon and select your account first and then register new API key as shown below



and let us register application with callback url as http://127.0.0.1:3000/auth/heroku/callback


Next, install the passport-heroku module using the command npm install passport-heroku. Once this is done, open app.js and add the following code near the top of the file.


var passport = require('passport');
var herokuStrategy = require('passport-heroku').Strategy;

var heroku_APP_ID = 'your app id';
var heroku_APP_SECRET = 'your app secret';


Add these line to app.js


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


Next, we need to configure the Facebook strategy. The strategy is configured by providing the clientIDclientSecret, and callbackURL as shown below.



passport.use(new HerokuStrategy({
        clientID: HEROKU_CLIENT_ID,
        clientSecret: HEROKU_CLIENT_SECRET,
        callbackURL: "http://127.0.0.1:3000/auth/heroku/callback"
    },
    function(accessToken, refreshToken, profile, done) {
        User.findOrCreate({ githubId: profile.id }, function(err, user) {
            return done(err, user);
        });
    }
));

process.nextTick() behaves much like setTimeout(). For more detailed info, take a look here. In the callback, we call done() with the user’s profile if they exist, or false otherwise

The next step is to set up routes for handling the Heroku authentication:
//handle response
app.get('/auth/heroku/callback',
    passport.authenticate('heroku', {
        successRedirect: '/success',
        failureRedirect: '/error'
    }));

When an authentication succeeds, a session is established and is maintained via a cookie. Passport will need to serialize and deserialize user instances to support sessions. Therefore, serializeUser and deserializeUser callbacks are also required.


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

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

Here all our app.js look like 




$ npm start





Fork complete code on Github 

What Others Are Reading