Skip to content

Instantly share code, notes, and snippets.

@leegee
Last active November 16, 2017 09:49
Show Gist options
  • Save leegee/0ddf2d1e2f544e9aa8d437e6539ad83d to your computer and use it in GitHub Desktop.
Save leegee/0ddf2d1e2f544e9aa8d437e6539ad83d to your computer and use it in GitHub Desktop.
Google Auth with Node.js JWT
const fetch = require('node-fetch');
const FormData = require('form-data');
const JSONWebToken = require('jsonwebtoken');
const getAuthToken = async function (args){
args.duration = args.duration || 60;
args.scope = args.scope instanceof Array? args.scope.join(' ') : args.scope;
let form = new FormData();
form.append('grant_type', 'urn:ietf:params:oauth:grant-type:jwt-bearer');
form.append('scope', args.scope);
form.append('assertion', JSONWebToken.sign(
{
iss : args.service_account_id,
scope : args.scope,
aud : 'https://accounts.google.com/o/oauth2/token'
},
args.private_key,
{
algorithm: 'RS256',
expiresIn: '1h'
}
));
let res = await fetch('https://accounts.google.com/o/oauth2/token', {
method: 'POST',
body: form
});
let json = await res.json();
console.log(json);
return 'Bearer ' + json.access_token;
}
const eg = async function () {
let authorization = await getAuthToken({
service_account_id : SERVICE_AC_ID,
private_key : PRIVATE_KEY,
scope : [
'https://www.googleapis.com/auth/plus.login',
'https://www.googleapis.com/auth/fusiontables',
'https://www.googleapis.com/auth/drive',
]
});
let apiResponse = await fetch(
'https://www.googleapis.com/fusiontables/v2/tables',
{
headers: { authorization }
}
);
let json = await apiResponse.json();
console.log(json);
return json;
};
eg();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment