DailyJS

Easier OAuth with Grant

Alex R. Young

Subscribe

@dailyjs

Facebook

Google+

libraries node modules express middleware oauth

Easier OAuth with Grant

Posted by Alex R. Young on .
Featured

libraries node modules express middleware oauth

Easier OAuth with Grant

Posted by Alex R. Young on .

OAuth always seems like an attractive alternative to rolling your own authentication, but it usually ends up being much harder than it looks. Grant (GitHub: simov/grant, License: MIT, npm: grant) by Simeon Velichkov aims to solve this. It's built on Guardian.js, which was made by Nijiko Yonskai at Mashape (Nijiko has written quite a few Node modules that I've written about).

Grant is Express middleware that accepts options for the OAuth server. You can include things like the permissions you want to request, so for Facebook this might include friends_groups:

"facebook": {
  "key": "...",
  "secret": "...",
  // by default request publish permissions via /connect/facebook
  "scope": ["publish_actions", "publish_stream"],
  // set specific callback route on your server for this provider only
  "callback": "/facebook/callback"
  // custom override keys
  "groups": {
    // request only group permissions via /connect/facebook/groups
    "scope": ["user_groups", "friends_groups"]
  },
  "pages": {
    // request only page permissions via /connect/facebook/pages
    "scope": ["manage_pages"],
    // additionally use specific callback route on your server for this override only
    "callback": "/pages/callback"
  }
}

One nice touch is you can provide options for different environment, so it's fairly easy to add settings for development or a CI server. Simeon has an app on Heroku that allows you to try out each provider with a friendly form: https://grant-oauth.herokuapp.com/.

I also noticed the same author has written a REST API wrapper called Purest. It embeds configuration details for dozens of providers, including Tumblr, Twitch, Google, and imgur.

To use it, you have to create an access token, then you can connect to a provider:

var Purest = require('purest');  
var google = new Purest({ provider:'google' });

google.get('channels', {  
  api: 'youtube',
  qs: {
    access_token: 'token',
    forUsername: 'user'
  }
}, function (err, res, body) {});

This Google instance can be used to access YouTube's API:

google.query('youtube')  
  .select('channels')
  .where({
    forUsername: 'username'
  })
  .auth('access-token')
  .request(function (err, res, body) {});

The documentation includes an excellent example that uses the request module's streaming API to pipe files from one service to another.