Getting different errors when try to run report for GA4 with regular account - google-analytics

I am trying to run a simple report on GA4 by using Google Analytics Data API Python client with a regular user credentials:
request = RunReportRequest(
property=f"properties/11111",
dimensions=[Dimension(name=f['name']) for f in report_definition['dimensions']],
metrics=[Metric(name=f['expression']) for f in report_definition['metrics']],
date_ranges=[DateRange(start_date=date, end_date=date)],
)
response = client.run_report(request)
And the client is BetaAnalyticsDataClient as also mentioned in the documentation:
credentials = Credentials(
token=None,
refresh_token=config['refresh_token'],
client_id=config['client_id'],
client_secret=config['client_secret'],
token_uri="https://accounts.google.com/o/oauth2/token",
scopes=["https://www.googleapis.com/auth/analytics.readonly"]
)
client = BetaAnalyticsDataClient(credentials=credentials)
It is not a Service Account so I am using google.oauth2.credentials.Credentials class as same in other Google APIs.
However, this operation is throwing an exception during the run_report function:
grpc._channel._InactiveRpcError: <_InactiveRpcError of RPC that terminated with:
status = StatusCode.UNAVAILABLE
details = "Getting metadata from plugin failed with error: ('invalid_grant: Bad Request', {'error': 'invalid_grant', 'error_description': 'Bad Request'})"
debug_error_string = "UNKNOWN:Error received from peer analyticsdata.googleapis.com:443 {created_time:"2023-01-14T14:12:10.907813+03:00", grpc_status:14, grpc_message:"Getting metadata from plugin failed with error: (\'invalid_grant: Bad Request\', {\'error\': \'invalid_grant\', \'error_description\': \'Bad Request\'})"}"
>
And when I try to use my access token in the credentials:
credentials = Credentials(
token=config["token"],
refresh_token=config['refresh_token'],
client_id=config['client_id'],
client_secret=config['client_secret'],
token_uri="https://accounts.google.com/o/oauth2/token",
scopes=["https://www.googleapis.com/auth/analytics.readonly"]
)
This time I am getting following error:
google.api_core.exceptions.Unauthenticated: 401 Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.
I am sure that my credentials is correct since I am using same account in my other repos.
Also, note that, I tried same operation with a service account and it does not give any error. However, for this purpose, I need to use a regular developer account since the OAuth flow is on a frontend project.
What are the suggestions on that issue? Is it possible to use a developer account in here and if yes, how?

I was able to fix the issue. The app just needs a sign-out sign-in (or refreshing the access token).

Related

Google_Drive_API_comments_error

Good afternoon. I am trying to write a function that will read the comments on a jpg file in google drive. However, when I try to run it it gives me the following error:
An error occurred:
<HttpError 403 when requesting https://www.googleapis.com/drive/v2/files/1SbB4VwCIhaS9mdJ_xqcyjenZfxxrpTsY/comments?alt=json returned "Insufficient Permission: Request had insufficient authentication scopes.". Details: "[{'domain': 'global', 'reason': 'insufficientPermissions', 'message': 'Insufficient Permission: Request had insufficient authentication scopes.'}]">
def retrieve_comments(service, file_id):
"""Retrieve a list of comments.
Args:
service: Drive API service instance.
file_id: ID of the file to retrieve comments for.
Returns:
List of comments.
"""
try:
comments = service.comments().list(fileId=file_id).execute()
return comments.get('items', [])
except errors.HttpError as error:
print('An error occurred: %s' % error)
return None
SCOPES = ['https://www.googleapis.com/auth/drive.file', 'https://www.googleapis.com/auth/drive', 'https://www.googleapis.com/auth/drive.file', ]
credentials = Credentials.from_authorized_user_file('token.json', SCOPES)
service = build('drive', 'v2', credentials=credentials)
print(retrieve_comments(service, '1SbB4VwCIhaS9mdJ_xqcyjenZfxxrpTsY'))
Update: this is what my token.json file looks like:
{"token": "ya29.a0ARrdaM-lbQRcrOHcWXHXVCZ--FHEBFmhetZy5mtKyE-KYg7kkqc7DCB3ELoGWm7DSFFqZ5n7MZ2qtpomhhhh3YjyPlDmFNiBFqW8jfzQcq2bUboJVHWly7w5KajgYBW6vXfpUG7XB-NiSRIGbgGXg7pADS9E", "refresh_token": "1//03RuSdM4_a83LCgYIARAAGAMSNwF-L9Ir99uSssRC7-EDBGOchESXQuY8uQh3BIAUSnUFmT60dipjtvqGslz9wyAl_OnLkoLWdko", "token_uri": "https://oauth2.googleapis.com/token", "client_id": "936594993582-hm55manlg9g4hkdeeisq6i4ogqk6are2.apps.googleusercontent.com", "client_secret": "irvWegrf57dztuP6_OigoGIT", "scopes": ["https://www.googleapis.com/auth/drive.metadata.readonly", "https://www.googleapis.com/auth/drive.file"], "expiry": "2021-08-19T12:26:14.658525Z"}
This is how my code looks like. any ideas why this might be happening and what I can do to solve it?
Edit: For anyone who runs into the same problem, remember the scopes in the quickstart must be the same as the ones in your python file.
Insufficient Permission
Means that the user you are authenticated with does not have permission to do what you are trying to do, or that user has not granted your application permission.
You are trying to use comments.list this method requires that you have been authorized with one of the following scopes
Now you appear to be using the following scopes
'https://www.googleapis.com/auth/drive.file', 'https://www.googleapis.com/auth/drive', 'https://www.googleapis.com/auth/drive.file',
Im not sure why you have drive.file twice, but lets ignore that for now.
As you can see you appear to be using the proper scopes needed by this endpoint. What i suspect has happened is that you have already authorized the user using a different set of scopes and you then changed the scopes in your application. When you change the scopes you need to be sure that you have revoked the users access in your application and prompt the user to authorize your application again. You are probably running on a stored access token and or refresh token which have the old scopes.
The solution will be to simply force your application to authorize your user again, make sure the consent screen popsup.

Microsoft Graph API - error 403 "Insufficient privileges to complete the operation"

I'm trying to use the AzureR family of R packages to interact with Outlook through the Graph API. Using Microsoft365R I have the following code:
outl <- get_business_outlook(
tenant = tenant_id,
app = client_id,
password = client_secret
)
But this results in a 403 error:
Error in process_response(res, match.arg(http_status_handler), simplify) :
Forbidden (HTTP 403). Failed to complete operation. Message:
Insufficient privileges to complete the operation.
The app in question has the API permissions Mail.ReadWrite, Mail.ReadWriteShared, Mail.Send, Mail.Send.Shared, offline_access, openid, User.Read.
I also tried using the AzureGraph package directly like:
login <- create_graph_login(
tenant = tenant_id,
app = client_id,
password = client_secret
)
This works and I get a token. I then try to extract user information with me <- login$get_user(), but this throws the same 403 error as above. I suspect there is something I need to do to actually authenticate the user, but I can't really figure out what.
I am entirely new to the Graph API so it's very possible that I have missed something obvious. Any help appreciated!
Microsoft365R/AzureGraph author here. In the code you show, both with get_business_onedrive() and create_graph_login(), you are authenticating as the app, not as the user. This means that there is no user account involved, hence you're unable to view user details or send email.
To authenticate as the user, run
# Microsoft365R
get_business_outlook("tenant_id", app="client_id")
# AzureGraph
create_graph_login("tenant_id", app="client_id")
ie, without the password argument. You should know it's working if R opens up a browser window for you to login to Azure (or to show it's successfully logged in).
The latest revision of the AzureAuth package has a vignette that explains a bit more on the various authentication scenarios. AzureAuth::get_azure_token is the underlying function used to obtain an OAuth token by Microsoft365R and AzureGraph, and you can pass down the arguments mentioned in the vignette from get_business_outlook and create_graph_login.

tweetinvi RegisterWebhookAsync 401 - Unauthorized - Authentication credentials were missing or incorrect

I am trying to use TweetInvi (4.0.3) to register a webhook:
var twitterCreditials = Auth.SetUserCredentials(twitterOptions.APIkey, twitterOptions.APISecretKey, twitterOptions.AccessToken, twitterOptions.AccessTokenSecret);
Webhooks.RegisterWebhookAsync("mydevenv", HttpUtility.UrlEncode("https://.../webhooks/twitter"), twitterCreditials);
But I get the following exception in response:
URL : https://api.twitter.com/1.1/account_activity/all/mydevenv/webhooks.json?url=https%3a%2f%2f...%2fwebhooks%2ftwitter
Code : 401
Error documentation description : Unauthorized - Authentication credentials were missing or incorrect.
Error message : https://api.twitter.com/1.1/account_activity/all/mydevenv/webhooks.json?url=https%3a%2f%2f...%2fwebhooks%2ftwitter web request failed.
Could not authenticate you. (32)
I've checked and double checked that my credentials are correct and I've followed the instructions here to create a dev environment. I've tried regenerating all my credentials for my Twitter app, but to no avail.
The error message suggests there is something wrong with my credentials, but I cannot see what.
I can see a log message when my webhook callback endpoint is called and it is not getting called.
I've also tried with version 5-beta of Tweetinvi:
var userClient = new TwitterClient("...", "...", "...", "...");
await userClient.AccountActivity.CreateAccountActivityWebhookAsync("mydevenv", "https://.../webhooks/twitter");
But this gives me a 400 for what appears to be the same call to the Twitter API as version 4.
There must be something simple I've missed?
You have to update user setup in your twitter project and set new permission to read/write .
Go to developer portl -> project -> setting -> User authentication settings -> select read/write permission

LinkedIn Access Token Being Used

I've successfully secured my access token for the LinkedIn API. However, when I try to use it to gather user information (currently just my own so I know that the profile has all public settings) using this code:
requestURL = 'https://api.linkedin.com/v2/people/(id:{my_linkedin_id})'
headers = {'Authorization': 'Bearer' + ' ' + access_token}
a = requests.get(requestURL,headers=headers)
could someone elaborate on any steps I might be messing?
When I run this code I keep getting a
<Response [404]>
You have 404 as response and in LinkedIn documentation you can see that:
404 Resource Not Found
This error occurs when your application tries to call an API or fetch
an entity that does not exist. For example, the API to get a friend’s
profile is /v2/people/id={personId}, not /v2/person/id={personId}. In
some cases (Ads, for example), a 404 error is returned when attempting
to access a restricted API. See 403 Access Denied and contact your
partner technical support channel if you continue to see the error.
I think you need too check if your link to resource is good.

RStudio & RGoogleAnalytics giving Error: redirect_uri_mismatch

I am trying to connect to google analytics from R through Analytics API. Following is my code.
library(RGoogleAnalytics)
oauth_token <- Auth(client.id = "clientID", client.secret = "clientSecret")
When I run above command it gives me following error in browser
Error: redirect_uri_mismatch
The redirect URI in the request, http://localhost:1410/, does not match the ones authorized for the OAuth client.
I have following settings in google developer console
Authorised JavaScript origins : http://localhost:1410
Authorised redirect URIs: http://localhost:8080/oauth2callback
Please help.
You will need to update your redirect URIs to the same port.
http://localhost:1410/oauth2callback
If that does not work, create a new client secret json file. Use "other" as the application type;

Resources