
Security News
Deno 2.2 Improves Dependency Management and Expands Node.js Compatibility
Deno 2.2 enhances Node.js compatibility, improves dependency management, adds OpenTelemetry support, and expands linting and task automation for developers.
The 'grant' npm package is a middleware for OAuth that allows you to easily integrate with various OAuth providers. It supports multiple frameworks like Express, Koa, Hapi, and more. It simplifies the process of setting up OAuth flows for authentication and authorization.
Express Integration
This code demonstrates how to integrate the 'grant' package with an Express application to handle OAuth authentication with Google. It sets up the necessary middleware and routes to handle the OAuth flow.
const express = require('express');
const session = require('express-session');
const Grant = require('grant-express');
const app = express();
app.use(session({secret: 'very secret'}));
app.use(new Grant({
defaults: {
protocol: 'http',
host: 'localhost:3000',
transport: 'session',
state: true
},
google: {
key: 'GOOGLE_CLIENT_ID',
secret: 'GOOGLE_CLIENT_SECRET',
scope: ['profile', 'email'],
callback: '/handle_google_callback'
}
}));
app.get('/handle_google_callback', (req, res) => {
res.json(req.session.grant.response);
});
app.listen(3000, () => {
console.log('Server listening on http://localhost:3000');
});
Koa Integration
This code demonstrates how to integrate the 'grant' package with a Koa application to handle OAuth authentication with GitHub. It sets up the necessary middleware and routes to handle the OAuth flow.
const Koa = require('koa');
const session = require('koa-session');
const Grant = require('grant-koa');
const app = new Koa();
app.keys = ['very secret'];
app.use(session(app));
app.use(new Grant({
defaults: {
protocol: 'http',
host: 'localhost:3000',
transport: 'session',
state: true
},
github: {
key: 'GITHUB_CLIENT_ID',
secret: 'GITHUB_CLIENT_SECRET',
scope: ['user'],
callback: '/handle_github_callback'
}
}));
app.use(async (ctx) => {
if (ctx.path === '/handle_github_callback') {
ctx.body = ctx.session.grant.response;
}
});
app.listen(3000, () => {
console.log('Server listening on http://localhost:3000');
});
Hapi Integration
This code demonstrates how to integrate the 'grant' package with a Hapi application to handle OAuth authentication with Twitter. It sets up the necessary middleware and routes to handle the OAuth flow.
const Hapi = require('@hapi/hapi');
const Grant = require('grant-hapi');
const start = async () => {
const server = Hapi.server({
port: 3000,
host: 'localhost'
});
await server.register({
plugin: Grant,
options: {
defaults: {
protocol: 'http',
host: 'localhost:3000',
transport: 'session',
state: true
},
twitter: {
key: 'TWITTER_CONSUMER_KEY',
secret: 'TWITTER_CONSUMER_SECRET',
callback: '/handle_twitter_callback'
}
}
});
server.route({
method: 'GET',
path: '/handle_twitter_callback',
handler: (request, h) => {
return request.yar.get('grant').response;
}
});
await server.start();
console.log('Server running on %s', server.info.uri);
};
start();
Passport is a popular authentication middleware for Node.js. It supports a wide range of authentication strategies, including OAuth, OAuth2, OpenID, and more. Compared to 'grant', Passport offers more flexibility and a larger ecosystem of strategies, but it can be more complex to set up.
Simple OAuth2 is a library for integrating OAuth2 authentication in Node.js applications. It provides a straightforward API for obtaining access tokens and refreshing them. Compared to 'grant', Simple OAuth2 is more focused on OAuth2 and does not support as many frameworks out of the box.
Bell is a Hapi plugin for third-party authentication using OAuth, OAuth2, and more. It is specifically designed for Hapi applications and provides a seamless integration with the Hapi framework. Compared to 'grant', Bell is more specialized for Hapi but does not support other frameworks.
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
npm install grant-express
var express = require('express')
var Grant = require('grant-express')
, grant = new Grant({/*configuration see below*/})
var app = express()
// mount grant
app.use(grant)
// other middlewares
app.use(cookieParser())
app.use(session())
npm install grant-koa
var koa = require('koa')
, mount = require('koa-mount')
// https://github.com/simov/grant/tree/master/example/koa-session
, session = require('any session store')
var Grant = require('grant-koa')
, grant = new Grant({/*configuration see below*/})
var app = koa()
// required: set the session store before mounting grant!
app.keys = ['keys']
app.use(session(...))
// mount grant
app.use(mount(grant))
// other middlewares
app.use(bodyParser())
npm install grant-hapi
var Hapi = require('hapi')
, yar = require('yar')
var Grant = require('grant-hapi')
, 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()
})
/connect/:provider/:override?
/connect/:provider/callback
{
"server": {
"protocol": "http",
"host": "localhost:3000",
"callback": "/callback",
"transport": "session",
"state": true
},
"provider1": {
"key": "...",
"secret": "...",
"scope": ["scope1", "scope2", ...],
"state": "some state",
"callback": "/provider1/callback"
},
"provider2": {...},
...
}
http
or https
localhost:3000
| dummy.com:5000
| mysite.com
.../callback
| /done
...querystring
| session
(defaults to querystring if omitted)true
| false
(OAuth2 only, defaults to false if omitted)facebook
| twitter
...
consumer_key
or client_id
of your appconsumer_secret
or client_secret
of your appserver
key)(additionally any of the reserved keys can be overriden for a provider)
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 OAuth flow, and provider
is the provider's name from the list of supported providers
This redirect
url is used internally by Grant. You will receive the response data from the OAuth flow in the route specified in the callback
key of your Grant configuration
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"
}
}
(these custom key names should be different than the reserved ones)
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 random state parameter on each authorization attempt
var state = (Math.floor(Math.random() * 999999) + 1)
res.redirect('/connect/facebook?state=' + state)
})
linkedin2
as a provider name, instead of linkedin
which is for OAuth1subdomain
optionaccess_type:'offline'
, Reddit - duration:'permanent'
, Trello - expiration:'never'
, and so on. Refer to the provider's OAuth documentation, and the Grant's OAuth configuration (search for custom_parameters
)In case you have a private OAuth provider that you don't want to be part of the officially supported ones, you can still define it in your configuration by adding a custom key for it
In this case you have to provide all of the required provider keys by yourself. Take a look at the OAuth configuration to see how the different types of flows are configured
{
"server": {
"protocol": "https",
"host": "mywebsite.com"
},
"custom1": {
"authorize_url": "https://mywebsite.com/authorize",
"access_url": "https://mywebsite.com/token",
"oauth": 2,
"key": "client_id",
"secret": "client_secret",
"scope": ["read", "write"]
}
}
You can easily configure different development environments
{
"development": {
"server": {"protocol": "http", "host": "dummy.com:3000"},
"facebook": {
"key": "development OAuth app credentials",
"secret": "development OAuth app credentials"
},
"twitter": {...}, ...
},
"staging": {
"server": {"protocol": "https", "host": "staging.mywebsite.com"},
"facebook": {
"key": "staging OAuth app credentials",
"secret": "staging OAuth app credentials"
},
"twitter": {...}, ...
},
"production": {
"server": {"protocol": "https", "host": "mywebsite.com"},
"facebook": {
"key": "production OAuth app credentials",
"secret": "production OAuth app credentials"
},
"twitter": {...}, ...
}
}
Then you can pass the environment flag
$ NODE_ENV=production node app.js
And use it in your application
var config = require('./config.json')
var grant = new Grant(config[process.env.NODE_ENV||'development'])
The OAuth data is returned as a querystring in your final callback (the one you specify in the callback
key of your Grant configuration)
Alternatively the response data can be returned in the session, see the configuration section above and the session transport example
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'
}
}
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'
}
}
In case of an error, the error
key will be populated with the raw error data
{
error:{
some:'error data'
}
}
callback/redirect
url always use this format
[protocol]://[host]/connect/[provider]/callback
config.json
file containing"server": {
"protocol": "https",
"host": "mywebsite.com"
},
"facebook": {
"key": "[APP_ID]",
"secret": "[APP_SECRET]",
"callback": "/handle_facebook_response"
},
"twitter": {
"key": "[CONSUMER_KEY]",
"secret": "[CONSUMER_SECRET]",
"callback": "/handle_twitter_response"
}
// Express
var express = require('express')
, Grant = require('grant-express')
, grant = new Grant(require('./config.json'))
var app = express()
app.use(grant)
// or Koa (see above)
// or Hapi (see above)
/connect/facebook
to initiate the OAuth flow for Facebook, or navigate to /connect/twitter
to initiate the OAuth flow for Twitter/handle_facebook_response
route for Facebook, and in the /handle_twitter_response
route for Twitter(also take a look at the examples)
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
})
MIT
v3.2.0 (2015/04/23)
FAQs
OAuth Proxy
The npm package grant receives a total of 174,461 weekly downloads. As such, grant popularity was classified as popular.
We found that grant demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Deno 2.2 enhances Node.js compatibility, improves dependency management, adds OpenTelemetry support, and expands linting and task automation for developers.
Security News
React's CRA deprecation announcement sparked community criticism over framework recommendations, leading to quick updates acknowledging build tools like Vite as valid alternatives.
Security News
Ransomware payment rates hit an all-time low in 2024 as law enforcement crackdowns, stronger defenses, and shifting policies make attacks riskier and less profitable.