Last active
May 9, 2018 19:34
-
-
Save rainabba/25d1972f455b71916952 to your computer and use it in GitHub Desktop.
google-api-nodejs-client examples using JWT and service account
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const README = '\n\nThis script is intended to help you use a google API \ | |
client_secret.json file to obtain an OAUTH token (json data) and \ | |
store it next to the source .json for future use. \n\n\ | |
To acomplish this, you will be given an URL that you can follow to \ | |
get a "code" which can then be used to get a token. As an I/O solution \ | |
I run this script with `node --inspect-brk` and then I catch the debugger \ | |
after the URL is logged to the console. Once I have the code, I can run \ | |
`code="{codeFromUrl}"` and resume the script. \n\n\n'; | |
console.log( README ); | |
// process.env.PATH_TO_CLIENT_SECRET_JSON is expected to have a valid path to a OAuth/Other/client_secret.json | |
// as provided by the steps at https://console.cloud.google.com/apis/credentials. A detailed tutorial can be | |
// found in Step 1 at https://developers.google.com/drive/v3/web/quickstart/nodejs. | |
const path = require('path'), | |
fs = require('fs'), | |
keyfile = path.normalize(path.join(__dirname, process.env.PATH_TO_CLIENT_SECRET_JSON )), | |
tokenfile = keyfile.replace(/\.json$/g, '') + '.token'; | |
keys = JSON.parse(fs.readFileSync(keyfile)), | |
scopes = ['https://www.googleapis.com/auth/drive'], | |
google = require('googleapis'); | |
let client = new google.auth.OAuth2( | |
keys.web.client_id, | |
keys.web.client_secret, | |
keys.web.redirect_uris[0] | |
), | |
code = null; | |
//Start with node --inspect-brk so you have time to hit this then retrieve the code and `code='{yournewcode}'` in the console | |
console.log( '\nGet code from:\n\n' + client.generateAuthUrl( { access_type: 'offline', scope: scopes } ) ); | |
console.log( '\nWhen you have that code, return and run `code="yourNewCode"` in the console and resume the debugger.\n\n' ); | |
debugger; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Updated after my 3rd attempt in 2 years to get Drive support in my node app, but being thwarted by volumes of confusing documents, conflicting examples and various approaches. As of 2018-05-09, this approach is "current" in that is uses the latest approach from the console, but it uses API v25 because v29 breaks completely with these samples and I can't find any docs that address those issues.