Skip to content

Instantly share code, notes, and snippets.

@daspilker
Created October 4, 2011 21:38
Show Gist options
  • Save daspilker/1262906 to your computer and use it in GitHub Desktop.
Save daspilker/1262906 to your computer and use it in GitHub Desktop.
Node.js script to retrieve an OAuth 2.0 access token
var express = require('express');
var oauth = require('oauth');
var oa;
var app = express.createServer();
app.get('/', function (req, res) {
res.end('<!DOCTYPE html><meta charset=utf-8><form action=/authorize><label>Client ID: <input type=text name=client_id required autofocus></label><br><label>Client Secret: <input type=text name=client_secret required></label><br><label>Scope: <input type=text name=scope required></label><br><input type=submit>');
});
app.get('/authorize', function (req, res) {
oa = new oauth.OAuth2(req.query.client_id,
req.query.client_secret,
"https://accounts.google.com/o",
"/oauth2/auth",
"/oauth2/token");
res.redirect(oa.getAuthorizeUrl({scope:req.query.scope, response_type:'code', redirect_uri:'http://localhost:8553/callback'}));
});
app.get('/callback', function(req, res) {
console.log(req.query.code);
oa.getOAuthAccessToken(req.query.code, {grant_type:'authorization_code', redirect_uri:'http://localhost:8553/callback'}, function(err, access_token, refresh_token) {
if (err) {
res.end('error: ' + JSON.stringify(err));
} else {
res.write('access token: ' + access_token + '\n');
res.write('refresh token: ' + refresh_token);
res.end();
}
});
});
app.listen(8553);
console.log('open http://localhost:8553');
{
"name": "get_access_token",
"version": "0.0.1",
"dependencies": {
"express": "2.4.6",
"oauth": "0.9.5"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment