I am creating an oauth2client in one function like so and returning it. I actually do pass in the clien id, secret, redirect url, and credentials. Those are all correct from what I have checked.
var OAuth2 = google.auth.OAuth2;
var oauth2Client = new OAuth2(CLIENT_ID, CLIENT_SECRET, REDIRECT_URL);
...
credentials = {
access_token: accessToken,
refresh_token: refreshToken
};
oauth2Client.setCredentials(credentials);
I then do this in the function where the oauth2client object is returned:
var plus = google.plus('v1');
console.log(JSON.stringify(oauth_client));
plus.people.get({ userId: 'me' , auth: oauth_client}, function(err, response) {
if(err) {
console.log(err);
} else {
console.log(JSON.stringify(response));
return response;
}
});
However I then get an error message saying that authClient.request is not a function.
TypeError: authClient.request is not a function
at createAPIRequest (/node_modules/googleapis/lib/apirequest.js:180:22)
I'm not sure why I get this error. I also did console.log(JSON.stringify(oauth_client)) to check for a request function and I didn't see any. Someone mentioned that this can't display the full prototype chain and that the request function might actually be there.
The problem is with "oauth_client".I used "google-auth-library" to authenticate.
var googleAuth = require('google-auth-library');
var auth = new googleAuth();
var oauth2Client = new auth.OAuth2(clientId, clientSecret, redirectUrl);
oauth2Client.credentials = credentials;
and then use this oauth2Client as oauth_client.
Not sure if you ever resolved this but try checking the scopes you have permissions for.
I was getting this error and turns out I had my scope set to 'https://www.googleapis.com/auth/youtube.readonly' and then when I changed my scope to 'https://www.googleapis.com/auth/youtube.upload' & 'https://www.googleapis.com/auth/youtube' I was able to upload videos instead of getting the error authClient.request is not a function
Related
i have a requirement for creating PostgreSQL instance using google SQL admin API, for the authentication, i want to use OAuth2Client in node js client library
function first() {
const oAuth2Client = new google.auth.OAuth2(
client_id,
client_secret,
redirect_uris[0]
);
var tkn = await oAuth2Client.getToken(code_from_another_user);
oAuth2Client.setCredentials(tkn);
return oAuth2Client;
});
function second(oAuth2Client)
{
var req = {
project: prjName,
resource: {
databaseVersion: "POSTGRES_13",
name: name,
region: cregion ,
gceZone: czone,
settings: {*****}
rootPassword: "xxxxx",
},
auth: oAuth2Client,
};
var crpsql = await sqlAdmin.instances.insert(req);
return crpsql;
});
function mainexec()
{
var a = first();
var b = second(a);
});
and i get this error
Error: No access, refresh token, API key or refresh handler callback
is set
here actually, i am trying to create a PostgreSQL instance on other google account cloud platform with there consent using OAuth2Client access token method. anyone please help? any supporting documentation?.
The function first returns oAuth2Client as it is . But in the function second it is converted to JSON object automatically.
so changed the function named second like this
function second(oAuth2Client)
{
var newoAuth2Client = new google.auth.OAuth2(
oAuth2Client._clientId,
oAuth2Client._clientSecret,
oAuth2Client.redirectUri
);
var tokenObj = {
access_token: oAuth2Client.credentials.tokens.access_token,
refresh_token: oAuth2Client.credentials.tokens.refresh_token,
};
newoAuth2Client.credentials = tokenObj;
var req = {
project: prjName,
resource: {
databaseVersion: "POSTGRES_13",
name: name,
region: cregion ,
gceZone: czone,
settings: {*****}
rootPassword: "xxxxx",
},
auth: newoAuth2Client,
};
var crpsql = await sqlAdmin.instances.insert(req);
return crpsql;
});
it worked like a magic.
I'm trying to use the google sheets API with oAuth2 in an express application. I've followed the basic setup to read data from a sheet but when I make a request, I get back an error that I'm missing an API key in the response.
As far as I can tell I am checking to see if a token is needed using the authorize() function and if it already exists, passing it in the request. Since the token should authenticate the request, why would I be getting this error?
*I have also already allowed access to the api through my account
checking authorization token
/**
* 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 {client_secret, client_id, redirect_uris} = credentials.installed;
const oAuth2Client = new google.auth.OAuth2(
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);
});
}
making a call to grab the sheet data
async function grabSheetData () {
const authClient = await authorize(creds, ()=>{console.log('success')});
const request = {
spreadsheetId: 'xxxxxxxxxxxxxxxxxxxxxxxxxx',
range: 'A1:C2',
valueRenderOption: 'ValueRenderOption.FORMATTED_VALUE',
dateTimeRenderOption: '[DateTimeRenderOption.SERIAL_NUMBER]',
auth: authClient, //this should be my token
}
try {
const response = (await sheets.spreadsheets.values.get(request)).data;
// TODO: Change code below to process the `response` object:
console.log(JSON.stringify(response, null, 2));
} catch (err) {
console.error(err);
}
};
grabSheetData();
You want to use Sheets API using the access token retrieved with OAuth2.
You want to achieve this using googleapis with Node.js.
You have already been able to retrieve the access token for using Sheets API.
If my understanding is correct, how about this answer? Please think of this as just one of several possible answers.
Modification points:
In your script, I think that authClient returns undefined. Because authorize has no returned values.
I think that this is the reason of your issue in your question.
Also, I think that when the correct authClient is returned, an error occurs at sheets.spreadsheets.values.get(request). Because the values of valueRenderOption: 'ValueRenderOption.FORMATTED_VALUE' and dateTimeRenderOption: '[DateTimeRenderOption.SERIAL_NUMBER]' are not correct.
When above points are reflected to your script, it becomes as follows.
Modified script:
authorize:
In this modification, I modified your script without modifying the function of getNewToken().
function authorize(credentials) {
return new Promise(resolve => { // Added
const { client_secret, client_id, redirect_uris } = credentials.installed;
const oAuth2Client = new google.auth.OAuth2(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, e => resolve(e)); // Modified
oAuth2Client.setCredentials(JSON.parse(token));
resolve(oAuth2Client); // Modified
});
});
}
grabSheetData:
async function grabSheetData() {
const authClient = await authorize(creds); // Modified
const request = {
spreadsheetId: 'xxxxxxxxxxxxxxxxxxxxxxxxxx',
range: "A1:C2",
valueRenderOption: "FORMATTED_VALUE", // Modified
dateTimeRenderOption: "SERIAL_NUMBER", // Modified
auth: authClient //this should be my token
};
try {
const response = (await sheets.spreadsheets.values.get(request)).data;
// TODO: Change code below to process the `response` object:
console.log(JSON.stringify(response, null, 2));
} catch (err) {
console.error(err);
}
}
grabSheetData();
Note:
In this modification, it supposes that creds and sheets have already been declared elsewhere. So please be careful this.
References:
ValueRenderOption
DateTimeRenderOption
If I misunderstood your question and this was not the direction you want, I apologize.
I,ve been using google-auth-library#0.10.0 nodejs just for verifying user identity in my api services, now it changed to 1.0 and everything is broken.
I previously used example from here:
https://developers.google.com/identity/sign-in/web/backend-auth
now I cannot figure out how to verify identity using the new library.
Examples here: https://github.com/google/google-auth-library-nodejs
explains how to get access to google apis, I just need to verify identity.
this is my code:
const GoogleAuth = require('google-auth-library');
const auth = new GoogleAuth.GoogleAuth();
const google = require('googleapis');
const authData = {
'googleAuth': {
'clientID': 'xxxxxxxxxxx-aaaaaaaaaaaaaaaaaaaaaa.apps.googleusercontent.com',
'clientSecret': 'sssssssssssssssssssssssss',
'callbackURL': 'http://localhost:121212/auth/'
}
};
const CLIENT_ID = authData.googleAuth.clientID;
function verifyToken(token) {
let tokenPromise = new Promise(function(resolve, reject) {
client.verifyIdToken(
token,
CLIENT_ID,
// Or, if multiple clients access the backend:
//[CLIENT_ID_1, CLIENT_ID_2, CLIENT_ID_3],
function(e, login) {
if (e) {
return reject(e);
} else {
var payload = login.getPayload();
var userid = payload['sub'];
//console.log(payload, userid, e, login);
return resolve(login);
// If request specified a G Suite domain:
//var domain = payload['hd'];
}
});
});
return tokenPromise;
};
it was working fine, just to get googleUserId.
now I've this error:
Error: This method accepts an options object as the first parameter, which includes the idToken, audience, and maxExpiry.
I understand I'm not passing properly parameters and maybe its not the method to use..but how can I know which method and how it accepts parameters??? I cannot find any documentation about google-auth-library#1.0...some one is using it in production??
The verifyIdToken changed. Here's a working example.
import { OAuth2Client } from 'google-auth-library';
const client = new OAuth2Client(
'xxxxxxxxxxx-aaaaaaaaaaaaaaaaaaaaaa.apps.googleusercontent.com,
'sssssssssssssssssssssssss',
'http://localhost:121212/auth/',
);
client.verifyIdToken({
idToken: TOKEN,
audience: CLIENT_ID_1 // If you have multiple [CLIENT_ID_1, CLIENT_ID_2, ...]
}, (err, login) => {
console.log(login);
});
Just tested this recently.
Google needs to update their documentation.
Please note that you can specify a maxAge to the verify id token options as well.
Here's the interface copied from the source code
export interface VerifyIdTokenOptions {
idToken: string;
audience: string|string[];
maxExpiry?: number;
}
As you can see the idToken and audience are required, the maxExpiry is optional.
Source can be found here
I am trying to setup nodejs with youtube analytics api. I am currently using a refresh token to try and get access tokens. It works great when using postman but I can't seem to replicate the functionality in nodejs and get a 400: invalid_request with no additional information provided.
Here is my code
var google = require('googleapis');
var OAuth2 = google.auth.OAuth2;
var oAuthClient = new OAuth2();
// Retrieve tokens via token exchange explained above or set them:
oAuthClient.setCredentials({
access_token: "",
refresh_token: process.env["YOUTUBE_ANALYTICS_REFRESHTOKEN"]
});
var youtubeAnalytics = google.youtubeAnalytics({
version: 'v1', auth: oAuthClient
});
var moduleExports = {
retrieveDailyBreakdownViews : function(){
var query = {
ids: 'channel==' + {channelID here},
'start-date': '2017-05-01',
'end-date': '2017-05-02',
metrics: 'views,estimatedMinutesWatched',
dimensions: 'insightPlaybackLocationType',
sort: 'views'
}
youtubeAnalytics.reports.query(query, (error, response) => {
console.log(error);
console.log(response);
});
}
}
module.exports = moduleExports;
Any ideas? If this doesn't work I can just try and build the query through HTTP/REST but I'd prefer to use the SDK.
In order to be able to refresh the access token, you will also need the client_id and client_secret. What's happening under the hood is the following request to refresh the token (referenced here):
POST https://accounts.google.com/o/oauth2/token
{
refresh_token: refresh_token,
client_id: this._clientId,
client_secret: this._clientSecret,
grant_type: 'refresh_token'
}
You'll need to initialize your Oauth2 client with :
var oAuthClient = new OAuth2(
YOUR_CLIENT_ID,
YOUR_CLIENT_SECRET,
YOUR_REDIRECT_URL
);
You'll also need to provide a refresh token that was generated using the same client_id / client_secret if you hardcode the refresh token value
This is what I ended up doing to fix the issue
var google = require('googleapis');
var googleAuth = require('google-auth-library');
var auth = new googleAuth();
var oauth2Client = new auth.OAuth2(process.env["YOUTUBE_CLIENT_ID"],
process.env["YOUTUBE_CLIENT_SECRET"]);
oauth2Client.credentials.refresh_token =
process.env["YOUTUBE_ANALYTICS_REFRESHTOKEN"];
var youtubeAnalytics = google.youtubeAnalytics({
version: 'v1'
});
I then make my calls like this:
youtubeAnalytics.reports.query(query, (error, response) => {})
I want to verify user google id on server side.So i want user google info by using google api.I have gone through all documentation but i stuck.I have seen this code,its working fine:
var google = require('googleapis');
var plus = google.plus('v1');
var OAuth2 = google.auth.OAuth2;
var oauth2Client = new OAuth2(CLIENT_ID, CLIENT_SECRET, REDIRECT_URL);
// Retrieve tokens via token exchange explained above or set them:
oauth2Client.setCredentials({
access_token: 'ACCESS TOKEN HERE',
refresh_token: 'REFRESH TOKEN HERE'
});
plus.people.get({ userId: 'me', auth: oauth2Client }, function(err, response) {
// handle err and response
});
but this is for google plus.I want to fetch user google profile with id not google plus info. Please help.
For googleapis version 19.0.0, you're gonna have to do something like this:
const googleapis = require('googleapis');
googleapis.people('v1').people.get({
resourceName: 'people/me',
personFields: 'emailAddresses,names',
auth: oauth2Client,
(err, response) => {
// do your thing
}
});
The fields resourceName and personFields are the ones that you might get error for saying that these are mandatory. You can find details on these here https://developers.google.com/people/api/rest/v1/people/get.
As for the scopes, following should be enough for this code snippet:
https://www.googleapis.com/auth/userinfo.email and
https://www.googleapis.com/auth/userinfo.profile