Google Api, Node.js - invalid_grant Malformed auth code - node.js

I'm trying to use the google api on node.js, but I always have the following error:
invalid_grant
Malformed auth code
By searching on the web I saw that the client id should be an email address, not the client id on the console. I changed that to the email address of my google account, it was even worse because I wasn't able to connect using google
Here's the code, adapted from https://developers.google.com/youtube/v3/docs/videos/list
var fs = require('fs');
var readline = require('readline');
var { google } = require('googleapis');
// var googleAuth = require('google-auth-library');
// If modifying these scopes, delete your previously saved credentials
// at ~/.credentials/google-apis-nodejs-quickstart.json
var SCOPES = ['https://www.googleapis.com/auth/youtube.force-ssl']
var TOKEN_DIR = (process.env.HOME || process.env.HOMEPATH ||
process.env.USERPROFILE) + '/.credentials/';
var TOKEN_PATH = TOKEN_DIR + 'google-apis-nodejs-quickstart.json';
// Load client secrets from a local file.
fs.readFile('client_secret.json', function processClientSecrets(err, content) {
if (err) {
console.log('Error loading client secret file: ' + err);
return;
}
// Authorize a client with the loaded credentials, then call the YouTube API.
//See full code sample for authorize() function code.
authorize(JSON.parse(content), {'params': {'id': 'Ks-_Mh1QhMc',
'part': 'snippet,contentDetails,statistics'}}, videosListById);
});
/**
* Create an OAuth2 client with the given credentials, and then execute the
* given callback function.
*
* #param {Object} credentials The authorization client credentials.
* #param {function} callback The callback to call with the authorized client.
*/
function authorize(credentials, requestData, callback) {
// Regarder response.config.data
var clientSecret = credentials.client_secret;
var clientId = credentials.client_id;
var redirectUrl = credentials.redirect_uri;
var auth = google.auth.OAuth2;
var oauth2Client = new google.auth.OAuth2(
clientId,
clientSecret,
redirectUrl
);
// Check if we have previously stored a token.
fs.readFile(TOKEN_PATH, function(err, token) {
if (err) {
getNewToken(oauth2Client, requestData, callback);
} else {
oauth2Client.credentials = JSON.parse(token);
callback(oauth2Client, requestData);
}
});
}
/**
* Get and store new token after prompting for user authorization, and then
* execute the given callback with the authorized OAuth2 client.
*
* #param {google.auth.OAuth2} oauth2Client The OAuth2 client to get token for.
* #param {getEventsCallback} callback The callback to call with the authorized
* client.
*/
function getNewToken(oauth2Client, requestData, callback) {
var authUrl = oauth2Client.generateAuthUrl({
access_type: 'offline',
scope: SCOPES
});
console.log('Authorize this app by visiting this url: ', authUrl);
var rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question('Enter the code from that page here: ', function(code) {
rl.close();
oauth2Client.getToken(code, function(err, token) {
if (err) {
console.log('Error while trying to retrieve access token');
console.log(err);
return;
}
oauth2Client.credentials = token;
storeToken(token);
callback(oauth2Client, requestData);
});
});
}
/**
* Store token to disk be used in later program executions.
*
* #param {Object} token The token to store to disk.
*/
function storeToken(token) {
try {
fs.mkdirSync(TOKEN_DIR);
} catch (err) {
if (err.code != 'EEXIST') {
throw err;
}
}
fs.writeFile(TOKEN_PATH, JSON.stringify(token));
console.log('Token stored to ' + TOKEN_PATH);
}
/**
* Remove parameters that do not have values.
*
* #param {Object} params A list of key-value pairs representing request
* parameters and their values.
* #return {Object} The params object minus parameters with no values set.
*/
function removeEmptyParameters(params) {
for (var p in params) {
if (!params[p] || params[p] == 'undefined') {
delete params[p];
}
}
return params;
}
/**
* Create a JSON object, representing an API resource, from a list of
* properties and their values.
*
* #param {Object} properties A list of key-value pairs representing resource
* properties and their values.
* #return {Object} A JSON object. The function nests properties based on
* periods (.) in property names.
*/
function createResource(properties) {
var resource = {};
var normalizedProps = properties;
for (var p in properties) {
var value = properties[p];
if (p && p.substr(-2, 2) == '[]') {
var adjustedName = p.replace('[]', '');
if (value) {
normalizedProps[adjustedName] = value.split(',');
}
delete normalizedProps[p];
}
}
for (var p in normalizedProps) {
// Leave properties that don't have values out of inserted resource.
if (normalizedProps.hasOwnProperty(p) && normalizedProps[p]) {
var propArray = p.split('.');
var ref = resource;
for (var pa = 0; pa < propArray.length; pa++) {
var key = propArray[pa];
if (pa == propArray.length - 1) {
ref[key] = normalizedProps[p];
} else {
ref = ref[key] = ref[key] || {};
}
}
};
}
return resource;
}
function videosListById(auth, requestData) {
var service = google.youtube('v3');
var parameters = removeEmptyParameters(requestData['params']);
parameters['auth'] = auth;
service.videos.list(parameters, function(err, response) {
if (err) {
console.log('The API returned an error: ' + err);
return;
}
console.log(response);
});
I literally copy-paste the code in the console, but still have the same error

Here is my case:
The authorization code in the url hash fragment is being encoded by encodeURIComponent API, so if you pass this code to request the access token. It will throw an error:
{ "error": "invalid_grant", "error_description": "Malformed auth code." }
So I use decodeURIComponent to decode the authorization code.
decodeURIComponent('4%2F_QCXwy-PG5Ub_JTiL7ULaCVb6K-Jsv45c7TPqPsG2-sCPYMTseEtqHWcU_ynqWQJB3Vuw5Ad1etoWqNPBaGvGHY')
After decode, the authorization code is:
"4/_QCXwy-PG5Ub_JTiL7ULaCVb6K-Jsv45c7TPqPsG2-sCPYMTseEtqHWcU_ynqWQJB3Vuw5Ad1etoWqNPBaGvGHY"

Generally the URL is Encoded, So decode the URL and try again
Try URL Encode/Decode Tool click here
In python it can be done as below:
import requests
from urllib.parse import unquote
# Decode the url
query_str = unquote(request.META.get('QUERY_STRING'))
# Or just decode CODE
code = unquote(code)
data_dict = {
"code": code, "redirect_uri":"", "grant_type": "authorization_code",
"client_id": "","client_secret": ""
}
resp = requests.post('https://oauth2.googleapis.com/token', data_dict)

Related

Not able to get oauth2 token information from google api

I'm able to get access oauth2 token from google api by using below code:
<html><head></head><body>
<script>
var YOUR_CLIENT_ID =
'568020407566-s1tdctjbjeocf5nt20l64midfo1atu4h.apps.googleusercontent.com';
var YOUR_REDIRECT_URI =
'https://us-central1-hyperledger-poc.cloudfunctions.net/oauthjax';
var fragmentString = location.hash.substring(1);
// Parse query string to see if page request is coming from OAuth 2.0 server.
var params = {};
var regex = /([^&=]+)=([^&]*)/g, m;
while (m = regex.exec(fragmentString)) {
params[decodeURIComponent(m[1])] = decodeURIComponent(m[2]);
}
if (Object.keys(params).length > 0) {
localStorage.setItem('oauth2-test-params', JSON.stringify(params) );
if (params['state'] && params['state'] == 'try_sample_request') {
trySampleRequest();
}
}
// If there's an access token, try an API request.
// Otherwise, start OAuth 2.0 flow.
function trySampleRequest() {
var params = JSON.parse(localStorage.getItem('oauth2-test-params'));
if (params && params['access_token']) {
var xhr = new XMLHttpRequest();
xhr.open('GET',
'https://www.googleapis.com' +
'access_token=' + params['access_token']);
xhr.onreadystatechange = function (e) {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log(xhr.response);
} else if (xhr.readyState === 4 && xhr.status === 401) {
// Token invalid, so prompt for user permission.
oauth2SignIn();
}
};
xhr.send(null);
} else {
oauth2SignIn();
}
}
/*
* Create form to request access token from Google's OAuth 2.0 server.
*/
function oauth2SignIn() {
// Google's OAuth 2.0 endpoint for requesting an access token
var oauth2Endpoint = 'https://accounts.google.com/o/oauth2/v2/auth';
// Create element to open OAuth 2.0 endpoint in new window.
var form = document.createElement('form');
form.setAttribute('method', 'GET'); // Send as a GET request.
form.setAttribute('action', oauth2Endpoint);
// Parameters to pass to OAuth 2.0 endpoint.
var params = {'client_id': YOUR_CLIENT_ID,
'redirect_uri': YOUR_REDIRECT_URI,
'scope': 'https://www.googleapis.com/auth/userinfo.email',
'state': 'try_sample_request',
'include_granted_scopes': 'true',
'response_type': 'token'};
// Add form parameters as hidden input values.
for (var p in params) {
var input = document.createElement('input');
input.setAttribute('type', 'hidden');
input.setAttribute('name', p);
input.setAttribute('value', params[p]);
form.appendChild(input);
}
// Add form to page and submit it to open the OAuth 2.0 endpoint.
document.body.appendChild(form);
form.submit();
}
</script>
<button onclick="trySampleRequest();">Try sample request</button>
</body></html>
I'm trying to get the token information using https://oauth2.googleapis.com/tokeninfo?id_token=XYZ123 mentioned in below google document
https://developers.google.com/identity/protocols/oauth2/openid-connect#validatinganidtoken
I'm getting below error as response:
{
"error_description": "Invalid Value"
}
But if i use the same token to get user info, it was working fine by using below code and the response as well
code which i tried:
const token = req.body.access_token;
var options = {
host: 'www.googleapis.com',
port: 443,
//path: '/oauth2/v3/userinfo',
path: '/oauth2/v3/tokeninfo?id_token='+token,
method: 'GET',
headers: {'Authorization': 'Bearer '+ token}
}
// making the https get call
let data;
var getReq = await https.request(options, function(response) {
response.on('data', (chunk) => {
data += chunk;
});
response.on('end', function() {
// Data reception is done, do whatever with it!
console.log("line 52");
// var parsed = JSON.parse(data);
console.log("line 54"+data);
res.send(data);
// console.log('data', parsed);
// console.log('endSTATUS: ' + parsed);
});
});
// console.log("response",recievedJSON);
/*getReq.on('end',function(){
res.send(valid);
});*/
getReq.end();
getReq.on('error', function(err) {
console.log('Error: ', err);
});
Response:
{
"sub": "1070944556782450037456",
"picture": "https://lh6.googleusercontent.com/-b32hSj9vONg/AAAAAAAAAAI/AAAAAAAAAAA/tasdfsadfBfIQ/photo.jpg",
"email": "xxxxxxxxx#gmail.com",
"email_verified": true
}

UnhandledPromiseRejectionWarning: ReferenceError: message is not defined Discord.js

I'm in the process of creating a Discord bot that will read from a specific Google Sheets spreadsheet and this error keeps coming up as I am trying to integrate the Google Sheets functions. See Github Repo and please know I'm extremely new at Node.js.
For this function, I have created index.js to get everything running for both discord.js and the Google API:
require("dotenv").config();
const fs = require("fs");
const Discord = require("discord.js");
const client = new Discord.Client();
const readline = require('readline');
const { google } = require('googleapis');
const OAuth2Client = google.auth.OAuth2;
const SCOPES = ['https://www.googleapis.com/auth/spreadsheets'];
const TOKEN_PATH = 'token.json';
/**
* Create an OAuth2 client with the given credentials, and then execute the
* given callback function.
* #param {Object} credentials The authorization client credentials.
* #param {function} callback The callback to call with the authorized client.
*/
const authorize = function (credentials, callback) {
const { client_secret, client_id, redirect_uris } = credentials.installed;
const oAuth2Client = new OAuth2Client(client_id, client_secret, redirect_uris[0]);
// Check if we have previously stored a token.
fs.readFile(TOKEN_PATH, (err, token) => {
if (err) return getNewToken(oAuth2Client, callback);
oAuth2Client.setCredentials(JSON.parse(token));
callback(oAuth2Client);
});
}
/**
* Get and store new token after prompting for user authorization, and then
* execute the given callback with the authorized OAuth2 client.
* #param {google.auth.OAuth2} oAuth2Client The OAuth2 client to get token for.
* #param {getEventsCallback} callback The callback for the authorized client.
*/
const getNewToken = function (oAuth2Client, callback) {
const authUrl = oAuth2Client.generateAuthUrl({
access_type: 'offline',
scope: SCOPES,
});
console.log('Authorize this app by visiting this url:', authUrl);
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
rl.question('Enter the code from that page here: ', (code) => {
rl.close();
oAuth2Client.getToken(code, (err, token) => {
if (err) return callback(err);
oAuth2Client.setCredentials(token);
// Store the token to disk for later program executions
fs.writeFile(TOKEN_PATH, JSON.stringify(token), (err) => {
if (err) console.error(err);
console.log('Token stored to', TOKEN_PATH);
});
callback(oAuth2Client);
});
});
}
//pulls all commands and events
fs.readdir("./events/", (err, files) => {
files.forEach(file => {
const eventHandler = require(`./events/${file}`);
const eventName = file.split(".")[0];
client.on(eventName, (...args) => eventHandler(client, ...args));
});
});
client.login(process.env.BOT_TOKEN);
module.exports = {
authorize,
google
}
Sheets.js contains the readAll function for Sheets I want to use so when someone types in assignments!all the function should run:
const {authorize, google} = require('./index');
const fs = require("fs");
const readline = require('readline');
const Discord = require("discord.js");
const client = new Discord.Client();
const spreadsheetId = "1asvhCVI1sC6Q2cCuqdUrRqFHkH2VCr5FM7kWSm8VBE8";
//read entire spreadsheet
const readAll = (range) => {
fs.readFile('client_secret.json', (err, content) => {
if (err) return console.log('Error loading client secret file:', err);
// Authorize a client with credentials, then call the Google Sheets API.
authorize(JSON.parse(content), (auth) => {
const sheets = google.sheets({ version: 'v4', auth });
sheets.spreadsheets.values.get({
spreadsheetId, range
}, (err, res) => {
if (err) return console.log('The API returned an error:' + err);
const rows = res.data.values;
if (rows.length) {
// Print columns B through F.
rows.map((row) => {
message.reply(`Details: ${row[0]}, Link: ${row[1]}, Additional Link: ${row[2]}, Assigned To: ${row[3]}, Assigned On: ${row[4]}, Ready for QC on: ${row[5]}, QC Link: ${row[6]}`);
});
} else {
console.log('No data found.');
}
});
});
});
}
module.exports = {
readAll
};
As I plan to have the bot do more functions in the future, I have created a message.js file in an events folder to call commands from a commands folder:
const assignments = require('../commands/assignments');
const assign = require('../commands/assign');
const qc = require('../commands/qc');
const qcList = require('../commands/qcList');
const sheets = require('../sheets');
module.exports = (client, message) => {
if (message.content.startsWith('assignments!')) {
return assignments(message);
} else if (message.content.startsWith('assign!')) {
return assign(message);
} else if (message.content.startsWith('qc!')) {
return qc(message);
} else if (message.content.startsWith('qclist!')) {
return qcList(message);
}
};
Assignments.js actually tells the bot that when the word "all" is used after the ! in "assignments!", that is when it is suppose to run the ReadAll function on the specific tab in the Sheets spreadsheet:
// gets all assignments or assignments based on name given after !
module.exports = (message, google, authorize, readAll) => {
const sheets = require('../sheets');
//ex message: assignments!Brody
//gets name after ! and stores as member variable
var messageContent = message.content;
var member = messageContent.split('!')[1];
var member = member.toLowerCase();
//test reading spreadsheet
if(member === 'all') {
sheets.readAll("Active News Assignments!B2:F");
}
//error messages
if (!member) {
message.reply("You must add a name or 'all' after the command.");
}
};
Again, I am very new to Node.js and following these tutorials to create this bot. Please feel free point out anything obvious I'm missing or ways I can simplify my code once it's working as I know I will be adding more functions in the future.
https://levelup.gitconnected.com/making-a-custom-discord-bot-in-discord-js-1e17f2090919
https://www.ishaanrawat.com/integrate-google-sheets-api-with-node-js/

middleware to send authorization token with all outbound requests in node js

I have a Express api which sends the request to other api's to get the information.Token is a jwt which expires every minute. So technically I have to attach new tokens in the header for each outbound request. Is there any way to attach authorization token in headers of all outbound requests.
route.js file:
'use strict';
router.get('/api/request', function (req, res) {
var Client = require('node-rest-client').Client;
var client = new Client();
client.post("http:/localhost:3000/client", args, function (data, response) {
console.log(response.status);
});
});
server.use(router);
};
This is a sample post request from one of the module made to other service from the api. Similar to this there are serveral other requests. I want to add the authorization token in the header for all the requests made from this api.
Try this, Creat One entry point(Service) for all API call and validate there. If the token has created before 45 seconds use same else regenerate new and use.
const Client = require('node-rest-client').Client;
const HttpService = (method, url, args) => {
return new Promise((resolve, reject) => {
var client = new Client();
if (method == 'POST') {
client.post(url, args, function (data, response) {
// If err reject(err)
resolve(response);
});
}
// Same for get and other
});
}
let basetoken, tokenExpire = Date.now() + 1000 * 45;
const getToken = async () => {
// Check token is generated before 45 Seconds or not
if (!basetoken || tokenExpire < Date.now()) {
basetoken = await HttpService('POST', 'Token URl', 'SomeData');
tokenExpire = Date.now() + 1000 * 45; // Token validity you can change this to some value
}
return basetoken;
}
const HttpPost = async (url, data) => {
const token = await getToken();
data.headers = {Token : token};
const data = await HttpService('POST', url, data);
return data;
}
module.exports ={ HttpPost }

Google Drive API Service Account inside domain

I have to download/upload/delete files from a folder on Drive with a Node.js server. That folder is inside the G Suite of the company, and only a few people in the company has access.
I have to use a Service Account to do this, the question is: is it possible? How can I do that?
I already read https://developers.google.com/drive/v2/web/delegation and https://developers.google.com/identity/protocols/OAuth2ServiceAccount
but I don't know if it is possible give permissions to a service account to access a folder inside the domain of the company, because the service account is #developer.gserviceaccount.com and the domain of the company is other, so gives me an error when I try to add that service account to the folder.
If you could guide me on this, I'll be very greatful.
Thanks!
You can use an oAuth token with the rights scope(s):
const path = require('path');
module.exports = (app) => {
const factory = {};
factory.connect = (done) => {
const fs = require('fs');
const google = require('googleapis');
const googleAuth = require('google-auth-library');
const SCOPES = [
'https://www.googleapis.com/auth/drive.metadata.readonly'
];
const TOKEN_DIR = path.resolve(app.root, 'server','config');
const TOKEN_PATH = path.resolve(TOKEN_DIR,'token.json');
const creds = require(path.resolve(app.root, 'server', 'config', 'google_oauth.json'));
authorize(creds, (ret) => {
done(null, ret);
});
/**
* Create an OAuth2 client with the given credentials, and then execute the
* given callback function.
*
* #param {Object} credentials The authorization client credentials.
* #param {function} callback The callback to call with the authorized client.
*/
function authorize(credentials, callback) {
const clientSecret = credentials.installed.client_secret;
const clientId = credentials.installed.client_id;
const redirectUrl = credentials.installed.redirect_uris[0];
const auth = new googleAuth();
const oauth2Client = new auth.OAuth2(clientId, clientSecret, redirectUrl);
// Check if we have previously stored a token.
fs.readFile(TOKEN_PATH, function (err, token) {
if (err) {
console.error('[ERROR] Unable to read token', err)
getNewToken(oauth2Client, callback);
} else {
oauth2Client.credentials = JSON.parse(token);
callback(oauth2Client);
}
});
}
/**
* Get and store new token after prompting for user authorization, and then
* execute the given callback with the authorized OAuth2 client.
*
* #param {google.auth.OAuth2} oauth2Client The OAuth2 client to get token for.
* #param {getEventsCallback} callback The callback to call with the authorized
* client.
*/
function getNewToken(oauth2Client, callback) {
const authUrl = oauth2Client.generateAuthUrl({
access_type: 'offline',
scope: SCOPES
});
console.log('Authorize this app by visiting this url: ', authUrl);
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question('Enter the code from that page here: ', function (code) {
rl.close();
oauth2Client.getToken(code, function (err, token) {
if (err) {
console.log('Error while trying to retrieve access token', err);
return;
}
oauth2Client.credentials = token;
storeToken(token);
callback(oauth2Client);
});
});
}
/**
* Store token to disk be used in later program executions.
*
* #param {Object} token The token to store to disk.
*/
function storeToken(token) {
try {
fs.mkdirSync(TOKEN_DIR);
} catch (err) {
if (err.code != 'EEXIST') {
throw err;
}
}
fs.writeFile(TOKEN_PATH, JSON.stringify(token));
console.log('Token stored to ' + TOKEN_PATH);
}
};
return factory
};
and then factory.connect(done) will give done an auth to use googleapis:
const google = require('googleapis');
const service = google.drive('v3');
service.files.list({
auth,
pageSize: 10,
fields: 'nextPageToken, files(id, name)'
}, step);

How to get user specific data on a Google Analytics request?

I'm trying to create a web app where a user can grant access to her Google Analytics account via OAuth2. After positive response I would like to make a request to that user's GA data (in the real application the request would be made "offline"). But when calling:
google.analytics('v3').data.ga.get(params, callback);
params should contain ids, which should be a list of "table ID"s from the user. How do I get hold of these IDs? Is it necessary to get this information through another profile-scoped-request?
Code:
var google = require('googleapis');
var OAuth2 = google.auth.OAuth2;
var clientId = '123-123.apps.googleusercontent.com';
var clientSecret = 'abc';
var redirectUrl = 'http://localhost:8080/redirect';
var authRequest = function(req, res) {
var oauth2Client = new OAuth2(clientId, clientSecret, redirectUrl);
var scopes = [ 'https://www.googleapis.com/auth/analytics.readonly' ],
params = { state: 'some-data', access_type: 'offline', scope: scopes };
var url = oauth2Client.generateAuthUrl(params);
res.redirect(301, url); // will return to "authResult()"
};
var _sampleAnalytics = function(req, res, oauthClient) {
var params = {
auth: oauthClient,
metrics: 'ga:visitors,ga:visits,ga:pageviews',
'start-date': '2015-06-01',
'end-date': '2015-06-30',
ids: ['ga:123456789'] // <== How to get this parameter?
};
google.analytics('v3').data.ga.get(params, function(err, response) {
// todo
});
};
var authResult = function (req, res) {
if (req.query.error) {
return handleError(res, req.query.error);
}
var oauth2Client = new OAuth2(clientId, clientSecret, redirectUrl);
oauth2Client.getToken(code, function(err, tokens) {
// Now tokens contains an access_token and an optional refresh_token. Save them.
if(err) {
return handleError(res, err);
} else {
oauth2Client.setCredentials(tokens);
_sampleAnalytics(req, res, oauth2Client);
}
});
};
Ok, that was simple. I just need to make another call to:
google.analytics('v3').management.accountSummaries.list(params, function(err, result) {
// ...
});
result will contain all the required information.

Resources