On a Ubuntu server I want to regularly execute a script which calls the Google Analytics Data API in order to extract the 20 most visited pages of a website.
- I have successfully installed the
gcloud
CLI (Google Cloud CLI) on my Ubuntu 24 server. - I have created a service account in my Google Cloud Account and a assigned a Google created secret Key to it and downloaded the key.json file (used for authentication later).
- In the relevant Google Analytics Admin section i created a new user (with the email address of the service account) that has at least read permission to the analytics data.
According to the Google Cloud CLI Documentation i created the following bash script:
#!/bin/bash
# Set environment variables
export KEY_FILE="/home/yesitsme/utilities/scripts/gcloud.json"
export PROPERTY_ID="278767000"
# Authenticate using the service account
gcloud auth activate-service-account --key-file=$KEY_FILE
# Get access token
ACCESS_TOKEN=$(gcloud auth print-access-token)
# Make API request for page views in the last 24 hours
curl -X POST \
"https://analyticsdata.googleapis.com/v1beta/properties/$PROPERTY_ID:runReport" \
-H "Authorization: Bearer $ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"dateRanges": [
{
"startDate": "yesterday",
"endDate": "today"
}
],
"dimensions": [
{
"name": "pagePath"
}
],
"metrics": [
{
"name": "screenPageViews"
}
],
"limit": 5
}'
If i execute the gcloud auth
command only, i see that the access token gets created successfully.
But when executing the script, i get this output with an error:
Activated service account credentials for: [[email protected]]
{
"error": {
"code": 403,
"message": "Request had insufficient authentication scopes.",
"status": "PERMISSION_DENIED",
"details": [
{
"@type": "type.googleapis.com/google.rpc.ErrorInfo",
"reason": "ACCESS_TOKEN_SCOPE_INSUFFICIENT",
"domain": "googleapis.com",
"metadata": {
"method": "google.analytics.data.v1beta.BetaAnalyticsData.RunReport",
"service": "analyticsdata.googleapis.com"
}
}
]
}
}
So the question is clear: why does my newly created service account have not enough permissions? Any hint?
oauth2l
for this purpose. Instead (!) ofgcloud auth activate-service-account
andACCESS_TOKEN=$(gcloud auth print-access-token)
, you should (!?) be able toACCESS_TOKEN=$(oauth2l fetch --credentials=${KEY_FILE} --scope=https://www.googleapis.com/auth/analytics)
.ACCESS_TOKEN=$(gcloud auth print-access-token)
(your original credentials) and browsinghttps://www.googleapis.com/oauth2/v1/tokeninfo?access_token=${ACCESS_TOKEN}
, this should have the default Cloud Platform scopes and not Google Analytics. Then use theACCESS_TOKEN
value usingoauth2l ....
and you should see Google Analytics scope.oauth2l
to view token scopes:oauth2l info --token ${ACCESS_TOKEN}