Coder Social home page Coder Social logo

grant's Introduction

Grant

npm-version coveralls-status

87 Supported Providers / OAuth Playground

500px | amazon | angellist | appnet | asana | assembla | basecamp | bitbucket | bitly | box | buffer | cheddar | coinbase | dailymile | dailymotion | deezer | deviantart | digitalocean | disqus | dropbox | edmodo | elance | eventbrite | evernote | everyplay | eyeem | facebook | feedly | fitbit | flattr | flickr | flowdock | foursquare | freshbooks | geeklist | getpocket | github | gitter | goodreads | google | harvest | heroku | imgur | instagram | jawbone | linkedin | live | mailchimp | meetup | mixcloud | moves | odesk | openstreetmap | paypal | podio | rdio | redbooth | reddit | runkeeper | salesforce | shopify | skyrock | slack | slice | soundcloud | spotify | stackexchange | stocktwits | stormz | strava | stripe | traxo | trello | tripit | tumblr | twitch | twitter | uber | vimeo | vk | withings | wordpress | xing | yahoo | yammer | yandex | zendesk

Express

npm install grant-express
var express = require('express')
var Grant = require('grant-express')

var grant = new Grant({...configuration see below...})

var app = express()
// mount grant
app.use(grant)
// app server middlewares
app.use(cookieParser())
app.use(session())

Koa

npm install grant-koa
var koa = require('koa')
var Grant = require('grant-koa')

var grant = new Grant({...configuration see below...})

var app = koa()
// mount grant
app.use(mount(grant))
// app server middlewares
app.use(session(app))
app.use(bodyParser())

Hapi

npm install grant-hapi
var Hapi = require('hapi')
var yar = require('yar')
var Grant = require('grant-hapi')

var grant = new Grant()
var server = new Hapi.Server()

server.register([{
  register: grant,
  options: {...configuration see below...}
}, {
  register: yar,
  options: {cookieOptions: {password:'password', isSecure:false}}
}], function (err) {
  server.start()
})

Reserved Routes for Grant

/connect/:provider/:override?
/connect/:provider/callback

Configuration

{
  "server": {
    "protocol": "http",
    "host": "localhost:3000",
    "callback": "/callback"
  },
  "provider1": {
    "key": "...",
    "secret": "...",
    "scope": ["scope1", "scope2", ...],
    "state": "some state",
    "callback": "/provider1/callback"
  },
  "provider2": {...},
  ...
}
  • server - configuration about your server
    • protocol - either http or https
    • host - your server's host name localhost:3000 | dummy.com:5000 | mysite.com ...
    • callback - common callback for all providers in your config /callback | /done ...
  • provider1 - any supported provider (see the list above) facebook | twitter ...
    • key - consumer_key or client_id of your app
    • secret - consumer_secret or client_secret of your app
    • scope - array of OAuth scopes to request
    • state - OAuth state string to send
    • callback - specific callback to use for this provider (overrides the global one specified under the server key)

Redirect Url

For callback/redirect url of your OAuth application you should always use this format

[protocol]://[host]/connect/[provider]/callback

Where protocol and host should match the ones from which you initiate the flow, and provider is the provider's name from the list of supported providers

The path you specify in the callback key in the Grant's configuration is where you'll receive the response data from the OAuth flow as a querystring, after the [protocol]://[host]/connect/[provider]/callback route have been hit

Static Overrides

You can add arbitrary {object} keys inside your provider's configuration to create sub configurations that override the global settings for that provider

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

Dynamic Override

Additionally you can make a POST request to the /connect/:provider/:override? route to override your provider's configuration dynamically on each request

<form action="/connect/facebook" method="post" accept-charset="utf-8">
  <input name="state" type="text" value="" />
  <input name="scope" type="checkbox" value="read" />
  <input name="scope" type="checkbox" value="write" />
  <button>submit</button>
</form>

Alternatively you can use a GET request with the /connect/:provider/:override? route

app.get('/connect_facebook', function (req, res) {
  // generate some random state parameter for each request
  var state = (Math.floor(Math.random() * 999999) + 1)

  res.redirect('/connect/facebook?state=' + state)
})

Quirks

  • To use LinkedIn's OAuth2 flow you should use linkedin2 for provider name, instead of linkedin which is for OAuth1
  • For Freshbooks, Shopify and Zendesk you should specify your company's sub domain name through the subdomain option
  • Some providers may employ custom authorization parameters outside of the ones specified in the configuration section. You can pass those custom parameters directly in your configuration, for example: Google - access_type:'offline', Reddit - duration:'permanent', Trello - expiration:'never', and so on. Refer to the provider's OAuth documentation, and the Grant's OAuth configuration for more details

Response Data

The OAuth data is returned as a querystring in your final callback (the one you specify in the callback key of your Grant configuration)

OAuth1

For OAuth1 the access_token and the access_secret are accessible directly, raw contains the raw response data

{
  access_token:'...',
  access_secret:'...',
  raw:{
    oauth_token:'...',
    oauth_token_secret:'...',
    some:'other data'
  }
}

OAuth2

For OAuth2 the access_token and the refresh_token (if present) are accessible directly, raw contains the raw response data

{
  access_token:'...',
  refresh_token:'...',
  raw:{
    access_token:'...',
    refresh_token:'...',
    some:'other data'
  }
}

Error

In case of an error, the error key will be populated with the raw error data

{
  error:{
    some:'error data'
  }
}

Typical Flow

  1. Register OAuth application on your provider's web site
  2. For callback/redirect url always use this format [protocol]://[host]/connect/[provider]/callback
  3. Create a config.json file containig
"server": {
  "protocol": "https",
  "host": "mywebsite.com",
  "callback": "/handle_oauth_response"
},
"facebook": {
  "key": "client_id",
  "secret": "client_secret",
  "scope": ["user_about_me"]
},
"twitter": {
  "key": "consumer_key",
  "secret": "consumer_secret",
  "callback": "/handle_twitter_response"
}
  1. Initialize Grant and mount it
// Express
var express = require('express')
var Grant = require('grant-express')
var grant = new Grant(require('./config.json'))
var app = express()
app.use(grant)
// or Koa
var koa = require('koa')
var Grant = require('grant-koa')
var grant = new Grant(require('./config.json'))
var app = koa()
app.use(mount(grant))
// or Hapi (see above)
  1. Navigate to /connect/facebook to initiate the OAuth flow for Facebook, or navigate to /connect/twitter to initiate the OAuth flow for Twitter
  2. Once the OAuth flow is complete for Facebook you'll receive the response data as a querystring in the /handle_oauth_response route, and for Twitter in the /handle_twitter_response route

What's Next

Once you have your access tokens secured, you can start making authorized requests on behalf of your users. Purest is a great REST API library that supports dozens of REST API providers

For example, you may want to get the user's profile after the OAuth flow has completed

var Purest = require('purest')
  , facebook = new Purest({provider:'facebook'})
  , twitter = new Purest({provider:'twitter',
    key:'[CONSUMER_KEY]', secret:'[CONSUMER_SECRET]'})

facebook.query()
  .get('me')
  .auth('[ACCESS_TOKEN]')
  .request(function (err, res, body) {
    // here body is a parsed JSON object containing things such as
    // id, first_name, last_name, gender, username and so on
  })

twitter.query()
  .get('users/show')
  .qs({screen_name:'nodejs'})
  .auth('[ACCESS_TOKEN]', '[ACCESS_SECRET]')
  .request(function (err, res, body) {
    // here body is a parsed JSON object containing things such as
    // id, screen_name and so on
  })

License

MIT

grant's People

Contributors

simov avatar francois2metz avatar grant avatar slaskis avatar

Watchers

James Cloos avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.