Passport.js (Node)

So now I know a little bit about routes and views (article coming soon), I decided it was time that authentication was needed. I know about OpenID (Oauth) and the preferred module appears to be passport.js. I decided to take a look and it seems very impressive, with support for facebook, twitter, google, tumblr, flickr, GItHub, reddit, youtube and about 30 others. Even the University of Warwick and Cambridge has support!

Installation

The usual command works, although there is an extra module to install for each provider, which are available here.
$ npm install passport
$ npm install passport-facebook
$ npm install passport-tumblr
And so on and henceforth. It’s so simple and easy, I didn’t actually expect it to work for some reason, as things are never this easy.

How to use it

I’ll talk about the providers that authenticate via OAuth tokens, since that’s what I’ve looked at so far. There are two stages to it, configuring passport and then authenticating requests.

Configuration

Passport.js requires a verify callback which takes the key and the secret and on successfully authenticating the app, you can go on to authenticating the user afterwards. Code taken from github,

passport.use(new TumblrStrategy({
    consumerKey: TUMBLR_CONSUMER_KEY,
    consumerSecret: TUMBLR_SECRET_KEY,
    callbackURL: "http://127.0.0.1:3000/auth/tumblr/callback"
  },
  function(token, tokenSecret, profile, done) {
    User.findOrCreate({ tumblrId: profile.id }, function (err, user) {
      return done(err, user);
    });
  }
));

Authentication

Once you have it configured, you literall just have to call this and then your app will know wether it has permission or not depending on if the user clicks allow or disallow for the permissions. Code taken from github,

app.get('/auth/tumblr',
  passport.authenticate('tumblr'));

app.get('/auth/tumblr/callback', 
  passport.authenticate('tumblr', { failureRedirect: '/login' }),
  function(req, res) {
    // Successful authentication, redirect home.
    res.redirect('/');
  });

Initial Thoughts

It seems to be a very nice/easy to use module that has a lot of features for an integral part of any website, since effectively all of the security is done through Google, Facebook etc, and odds are that me and you cannot make things as secure as them. After the security part, there’s the nice little ‘Oh yay, I don’t have to type my email again’ functionality, which I think a lot more sites need to provide.

About these ads

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s