Node.js - Display my own google analytics data to visitors - node.js

I am struggling to authenticate on server side.
I would like to display my own data from Google Analytics to my site's visitors.
Every manual, API, or tutorial I can find explains how to use OAUTH2 to authenticate users.
ie: https://github.com/google/google-api-nodejs-client#alpha
https://developers.google.com/analytics/devguides/reporting/embed/v1/core-methods-reference
https://developers.google.com/analytics/devguides/reporting/core/v2/authorization
and so on.
With that, I do not need to authenticate users because it's not their accounts I would like to access, but rather my own.
This is what I am using:
var google = require('googleapis');
var scopes = ['https://www.googleapis.com/auth/analytics.readonly']
var OAuth2 = google.auth.OAuth2;
var oauth2Client = new OAuth2(auth.googleAPI);
var analytics = google.analytics("v3")
console.log(analytics.data.ga.get({
ids:"ga:107290894",
"start-date":"2016-01-01",
"end-date":"2017-04-15",
"metrics":'ga:sessions,ga:pageviews',
}))
But I get the following error:
{ [Error: Login Required]
code: 401,
errors:
[ { domain: 'global',
reason: 'required',
message: 'Login Required',
locationType: 'header',
location: 'Authorization' } ] }
through auth.googleAPI I am passing the client id, secret and public key, and every other piece of information that was in the JSON file I got from google when I created a Service Account Key.
What am I doing wrong?

While it is incredibly unclear in the documentation, it turns out that I needed to use the JWT (Service Tokens) provided with googleapis.
Hope this helps.

Related

How to use googleapis google.auth.GoogleAuth() for google API service account in Twilio serverless function?

How to use googleapis google.auth.GoogleAuth() for google API service account in Twilio serverless function, since there is no FS path to provide as a keyFile value?
Based on the example here ( https://www.section.io/engineering-education/google-sheets-api-in-nodejs/ ) and here ( Google api node.js client documentation ) my code is based on the example here ( Receive an inbound SMS ) and looks like...
const {google} = require('googleapis')
const fs = require('fs')
exports.handler = async function(context, event, callback) {
const twiml = new Twilio.twiml.MessagingResponse()
// console.log(Runtime.getAssets()["/gservicecreds.private.json"].path)
console.log('Opening google API creds for examination...')
const creds = JSON.parse(
fs.readFileSync(Runtime.getAssets()["/gservicecreds.private.json"].path, "utf8")
)
console.log(creds)
// connect to google sheet
console.log("Getting googleapis connection...")
const auth = new google.auth.GoogleAuth({
keyFile: Runtime.getAssets()["/gservicecreds.private.json"].path,
scopes: "https://www.googleapis.com/auth/spreadsheets",
})
const authClientObj = await auth.getClient()
const sheets = google.sheets({version: 'v4', auth: authClientObj})
const spreadsheetId = "myspreadsheetID"
console.log("Processing message...")
if (String(event.Body).trim().toLowerCase() == 'KEYWORD') {
console.log('DO SOMETHING...')
try {
// see https://developers.google.com/sheets/api/guides/values#reading_a_single_range
let response = await sheets.spreadsheets.values.get({
spreadsheetId: spreadsheetId,
range: "'My Sheet'!B2B1000"
})
console.log("Got data...")
console.log(response)
console.log(response.result)
console.log(response.result.values)
} catch (error) {
console.log('An error occurred...')
console.log(error)
console.log(error.response)
console.log(error.errors)
}
}
// Return the TwiML as the second argument to `callback`
// This will render the response as XML in reply to the webhook request
return callback(null, twiml)
...where the Asset referenced in the code is for a JSON generated from creating a key pair for a Google APIs Service Account and manually copy/pasting the JSON data as an Asset in the serverless function editor web UI.
I see error messages like...
An error occurred...
{ response: '[Object]', config: '[Object]', code: 403, errors: '[Object]' }
{ config: '[Object]', data: '[Object]', headers: '[Object]', status: 403, statusText: 'Forbidden', request: '[Object]' }
[ { message: 'The caller does not have permission', domain: 'global', reason: 'forbidden' } ]
I am assuming that this is due to the keyFile not being read in right at the auth const declaration (IDK how to do it since all the example I see assume a local filepath as the value, but IDK how to do have the function access that file for a serverless function (my attempt in the code block is really just a shot in the dark)).
FYI, I can see that the service account has an Editor role in the google APIs console (though I notice the "Resources this service account can access" has the error
"Could not fund an ancestor of the selected project where you have access to view a policy report on at least one ancestor"
(I really have no idea what that means or implies at all, very new to this)). Eg...
Can anyone help with what could be going wrong here?
(BTW if there is something really dumb/obvious that I am missing (eg. a typo) just LMK in a comment so can delete this post (as it would then not serve any future value of others))
The caller does not have permission', domain: 'global', reason: 'forbidden
This actually means that the currently authenticated user (the service account) does ot have access to do what you are asking it to do.
You are trying to access a spread sheet.
Is this sheet on the service accounts google drive account? If not did you share the sheet with the service account?
The service account is just like any other user if it doesn't have access to something it cant access it. Go to the google drive web application and share the sheet with the service account like you would share it with any other user just use the service account email address i think its called client id its the one with an # in it.
delegate to user on your domain
If you set up delegation properly then you can have the service account act as a user on your domain that does have access to the file.
delegated_credentials = credentials.with_subject('userWithAccess#YourDomain.org')

Node.js - Can't access my account from the Google Drive API

I need to programmatically modify my Google Drive, in terms of the ability to create folders and uploading to them a bunch of files, and then, when needed - remove that root folder and redo the whole process.
I've created a project that has a service account, then downloaded the JSON and it's stored on my computer.
Next, I followed this tutorial.
I ended up with this code:
const auth = await google.auth.getClient({
credentials: require(pathToServiceAccountJSON),
scopes: "https://www.googleapis.com/auth/drive"
});
const drive = await google.drive({ version: "v3", auth });
drive.files
.create({
resource: {
name: filename,
mimeType: "application/vnd.google-apps.folder",
parents: [parentId]
}
})
.then(result => console.log("SUCCESS:", result))
.catch(console.error);
However, executing it causing the following error to be thrown:
{
...
errors: [{
domain: "global",
reason: "forbidden",
message: "Forbidden"
}]
}
First off, if you get lost, this quick start from Google is probably better than the tutorial.
Secondly, to get access to your drive you must request the appropriate scope within your app, and you must authorize the app's requested permissions (scopes) by visiting a URL that will be provided during the authorization process. Here is a guide to scopes.
To be able to impersonate a user(like yourself or any other in a domain) with a service account you need to have it with domain-wide delegation on, to do this you need to have a G suite account [1]. If this is the case, from the library example [2], you need to add the user you want to impersonate as the 5th parameter when constructing the JWT object:
const {JWT} = require('google-auth-library');
const keys = require('./jwt.keys.json');
async function main() {
const client = new JWT(
keys.client_email,
null,
keys.private_key,
['https://www.googleapis.com/auth/cloud-platform'],
'userToImpersonate#example.com'
);
const url = `https://dns.googleapis.com/dns/v1/projects/${keys.project_id}`;
const res = await client.request({url});
console.log(res.data);
}
If you don't have G Suite account, you could simply follow the quickstart [3] steps to get drive service and then make your create request with it.
[1] Do I need G Suite account to make requests impersonating an user with a service account?
[2] https://github.com/googleapis/google-auth-library-nodejs#json-web-tokens
[3] https://developers.google.com/drive/api/v3/quickstart/nodejs

Verify JWT from Google Chat POST request

I have a bot in NodeJS connected to Google Chat using HTTPs endpoints. I am using express to receive requests. I need to verify that all requests come from Google, and want to do this using the Bearer Token that Google Sends with requests.
My problem is that I am struggling to find a way to verify the tokens.
I have captured the token and tried a GET reuqes to https://oauth2.googleapis.com/tokeninfo?id_token=ey... (where ey... is the token start).
Which returns:
"error": "invalid_token",
"error_description": "Invalid Value"
}
I have tried what Google recommends:
var token = req.headers.authorization.split(/[ ]+/);
client.verifyIdToken({
idToken: token[1],
audience: JSON.parse(process.env.valid_client_ids)
}).then((ticket) => {
gchatHandler.handleGChat(req.body, res);
}).catch(console.error);
And get the following error:
Error: No pem found for envelope: {"alg":"RS256","kid":"d...1","typ":"JWT"}
Any idea where I should head from here?
Edit: https://www.googleapis.com/service_accounts/v1/metadata/x509/chat#system.gserviceaccount.com found this, investigating how to use it. The kid matches the one I get.
Worked it out, eventually.
You need to hit: https://www.googleapis.com/service_accounts/v1/metadata/x509/chat#system.gserviceaccount.com to get a JSON file containing the keys linked to their KIDs.
Then when a request arrives, use jsonwebtoken (NPM) to decode the token and extract the KID from the header.
Use the KID to find the matching public key in the response from the website above, then use the verify function to make sure the token matches the public key.
You also need to pass the audience and issuer options to verify, to validate that it is your particular service account hitting the bot.
The solution above maybe the correct for Google Chat, but in my experience Google services (e.g. Google Tasks) use OIDC tokens, which can be validated with verifyIdToken function.
Adding my solution here, since your question/answer was the closest thing I was able to find to my problem
So, In case if you need to sign a request from your own code
on client, send requests with OIDC token
import {URL} from 'url';
import {GoogleAuth} from 'google-auth-library';
// will use default auth or GOOGLE_APPLICATION_CREDENTIALS path to SA file
// you must validate email of this identity on the server!
const auth = new GoogleAuth({});
export const request = async ({url, ...options}) => {
const targetAudience = new URL(url as string).origin;
const client = await auth.getIdTokenClient(targetAudience);
return await client.request({...options, url});
};
await request({ url: 'https://my-domain.com/endpoint1', method: 'POST', data: {} })
on the server, validate OIDC (Id token)
const auth = new OAuth2Client();
const audience = 'https://my-domain.com';
// to validate
const token = req.headers.authorization.split(/[ ]+/)[1];
const ticket = await auth.verifyIdToken({idToken: token, audience });
if (ticket.getPayload().email !== SA_EMAIL) {
throw new Error('request was signed with different SA');
}
// all good
Read more about Google OpenID Connect Tokens

Accessing Office365 API with Client Credentials Flow

I am trying to develop a node application that would be able to access my Outlook.com mails.
I am trying to do it in a way it doens't require me to enter my credentials, the application will know them (user name and password). I am not too worried about storing them in the config of my application.
I am using simple-oauth2 but I keep getting an error. The following is the code that is trying to retrieve the Oauth token:
const credentials = {
client: {
id: this.appId,
secret: this.appSecret,
},
auth: {
tokenHost: "https://login.microsoftonline.com",
authorizePath: "common/oauth2/v2.0/authorize",
tokenPath: "common/oauth2/v2.0/token",
},
};
const oathClient = oauth2.create(credentials);
const tokenConfig = {
username: "zzz#outlook.com",
password: "xxxxx",
scope: "Mail.Read",
};
const result = await oathClient.ownerPassword.getToken(tokenConfig);
const token = oathClient.accessToken.create(result);
However when calling get token I get the following response:
"error": "invalid_grant",
"error_description": "AADSTS70000: The grant is not supported by this API version\r\nTrace ID: 91935472-5d7b-4210-9a56-341fbda12a00\r\nCorrelation ID: 6b075f4e-b649-493e-a87b-c74f0e427b47\r\nTimestamp: 2017-08-19 14:00:33Z",
"error_codes": [ 70000],
I have aded the application in apps.dev.microsoft.com
Added a platform (Web API) for it.
Added the "Mail.Read" permission on Microsoft Grah
And I am using the apikey and secret I generated there.
Googling looks like all the examples I find are to connect is using a client certificate. Is it possible to use the API using the API credentials?
If the only way is using certificates, is there a way I can use simple-oauth2 for that?
Ok, looks like I was using the wrong method.
Trying to access using the ClientCredentials module on simple-ouath2 and its workign now:
const tokenConfig = {
scope: "https://graph.microsoft.com/.default",
};
const result = await oathClient.clientCredentials.getToken(tokenConfig);

Getting Error: unauthorized_client when trying to authorize script

I've created service account with domain wide delegation and its scopes (in Admin console and Developer console) as described in documentation. I've been trying this for a week now and I am stuck. This is my code:
const google = require('googleapis');
const gmail = google.gmail('v1');
const directory = google.admin('directory_v1');
const scopes = [
'https://www.googleapis.com/auth/gmail.readonly',
'https://www.googleapis.com/auth/admin.directory.user.readonly'
];
const key = require('./service_key.json');
var authClient = new google.auth.JWT(
key.client_email,
key,
key.private_key,
scopes,
"kruno#example.com"
);
authClient.authorize(function(err, tokens){
if (err) {
console.log(err);
return;
}
// API call methods here...
});
I get this error:
Error: unauthorized_client
I am unable to understand:
Is this proper technique for calling Google API methods from server-side scripts without any user interaction? (under domain only)
How do service account and actual user account communicate this way?
I heard about callback URI, am I missing it?
I think you are missing the final step which is giving access to your application in the control panel of your domain.
You can follow doc properly to activate it with your application
https://developers.google.com/+/domains/authentication/delegation
Also you can start with your first call step here
https://developers.google.com/adwords/api/docs/guides/first-api-call

Resources