Failed to refresh Access Token when using Google OAuth2.0 credentials - google-analytics

I am trying to use GA4 API (with Google Python Client & Google Analytics Data Python Client) of Google with the Credentials authentication:
credentials = Credentials(
token=config['access_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 is working when my access token is not expired. However, this access token is expiring after 1 hour and I want to refresh it via following method:
credentials.refresh(google.auth.transport.requests.Request())
However, this code is returning "invalid_grant" error.
For that problem, I checked almost everything suggested (i.e. system clock/ntp, user permissions, etc.) however I couldn't fix the problem.
Also, I can't figure out about the refresh_token that I use is valid for Google Analytics 4 or not.
So, the questions are:
How can I able to solve this problem?
How can I assure that the refresh_token is valid for GA4?
If not valid, how can I refresh the refresh_token?
Is there any suggestion on the refresh of access_token, any other method or anything else?
Thanks

In my case, the solution was creating new OAuth client and generate a refresh_token for that account depend on the Google Analytics scope.
For that purpose, after I create the new client, I downloaded the client_secrets.json and run the Complete Example by Google and finally I am able to refresh the token.

Related

'Token has been expired or revoked' - Google OAuth2 Refresh token gets expired in a few days

I am using Google Analytics API to fetch analytics data. I tried to authenticate it using following steps:
Created OAuth client ID in https://console.developers.google.com/ credentials section.
In consent screen I had set publishing status as testing
In OAuth 2.0 Playground I got the refresh token using above generated client id and client secret
Then I am using it to generate access token through it.
But after a few days, the refresh token expires although it is mentioned that the refresh token's validity is life long.
If your app is in testing mode then user tokens will expire in 7 days. Please find this explanations here: https://support.google.com/cloud/answer/10311615#zippy=%2Ctesting
I needed to send mails from a gmail account that I have access to, using nodemailer. It works for a couple of days before my refresh token is mysteriously revoked, even though the account belongs to me. A google search brought me here and I had been watching for a while hoping someone would help with a solution.
As you mentioned, this seems to happen with only test/unverified apps and I'm guessing google revokes tokens for such applications in your account after a few days. After much trials and errors, here is what I did.
NOTE: This is solution is only applicable to accounts you own, otherwise you must verify your app to access other people's accounts
Generate a new refresh token (existing one is most likely revoked) as described in this SO post
Go to the security tab of your google account dashboard
Under the Recent security activity section, you should see a security alert for your app.
Click on the context menu next to the notification and click DISMISS
At this point you'll be presented with a dialog of options where you indicate the level of trust you have for the app. I just went ahead and said I trusted the developer/app, obviously. And that's it! The refresh token should persist after this.
I could not find anything related anywhere else.
The other answer pointed me in the right direction but for me the option was located somewhere else: security > security checkup/security issues found > context menu next to your app > dismiss
This issue seems to be for unverified apps, Simply delete the token file from your project and rerun the project, it will create a new token.
My problem was when I've added access_token instead of refresh_token.
What I did:
Go to https://console.cloud.google.com/apis/credentials/consent and change from the testing status to published.
Delete the current token file.
Authorize the API again by signing into your gmail account. You will be sent to a warning screen. From there, you can choose to proceed.
When done you'll get a new token file
The solution is to delete your token.json file to force Google to find a new token.
I was able to get it to work WITHOUT a verified app. Perhaps the refresh() method will work once my app is verified. Not sure on that one.

access_token for Google Analytics API

I want to get a access_token to get information from Google Analytics API by passing it in the browser . I am not able to find the correct documentation anywhere. I have tried multiple ways but nothing seems to work. As of now, I got tokens via Google Analytics Query Explorer and it works for 60 minutes. I am looking for a permanent token or a token which is valid for a more period of time.
In order to access private Google analytics data you need to be authorized. In order to be authorized you use something called Oauth2
The initial request will look something like this. It will allow the user to consent to your applications access to their data
GET https://accounts.google.com/o/oauth2/auth?client_id={clientid}.apps.googleusercontent.com&redirect_uri=urn:ietf:wg:oauth:2.0:oob&scope=https://www.googleapis.com/auth/analytics.readonly&response_type=code
Once the user has consented to your accessing their data, you will be given an authorization code.
Once you have the authorization code you can exchange it for an access token. This is a http post request.
POST https://accounts.google.com/o/oauth2/token
code=4/X9lG6uWd8-MMJPElWggHZRzyFKtp.QubAT_P-GEwePvB8fYmgkJzntDnaiAI&client_id={ClientId}.apps.googleusercontent.com&client_secret={ClientSecret}&redirect_uri=urn:ietf:wg:oauth:2.0:oob&grant_type=authorization_code
The response should then look something like this.
{
"access_token" : "ya29.1.AADtN_VSBMC2Ga2lhxsTKjVQ_ROco8VbD6h01aj4PcKHLm6qvHbNtn-_BIzXMw",
"token_type" : "Bearer",
"expires_in" : 3600,
"refresh_token" : "1/J-3zPA8XR1o_cXebV9sDKn_f5MTqaFhKFxH-3PUPiJ4"
}
The access token will work for one hour.
I recommend looking for a sample and a client library in your chosen programming language so that you dont have to do all this manually most of the libraries are designed to handle authentication and authorization for you.

Google Calendar API - Continuous syncing

I know how to sync with Google Calendar API. We are trying to build a system where to sync the Google Calendar continuously without asking for the consent screen.
I did search a lot but it seems they sent nextsynctoken to get the full event list. but If I want to restart the sync after 2 weeks. how can I do it? without asking auth window or consent screen to the user?
Please let me know if its possible.
Thank you in advance
Saravana
All requests you are making to the Google Calendar API must be authorized by an authenticated user.
But since you are encountering a problem that looks like token expiration to me, why don't you try and refresh the access tokens you are using?
According to the Using OAuth 2.0 to Access Google APIs documentation
Access tokens have limited lifetimes. If your application needs access to a Google API beyond the lifetime of a single access token, it can obtain a refresh token. A refresh token allows your application to obtain new access tokens.
The nextSyncToken is a piece of data exchanged between the server and the client, and is used in the synchronization process.
You can keep on using the nextSyncToken but you will have to use a refresh token in order for you to not use the consent screen every time.
Here is a sample code from the Using OAuth 2.0 for Web Server Applications used to exchange authorization code for refresh and access tokens, using Python:
state = flask.session['state']
flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file(
'client_secret.json',
scopes=['https://www.googleapis.com/auth/youtube.force-ssl'],
state=state)
flow.redirect_uri = flask.url_for('oauth2callback', _external=True)
authorization_response = flask.request.url
flow.fetch_token(authorization_response=authorization_response)
# Store the credentials in the session.
# ACTION ITEM for developers:
# Store user's access and refresh tokens in your data store if
# incorporating this code into your real app.
credentials = flow.credentials
flask.session['credentials'] = {
'token': credentials.token,
'refresh_token': credentials.refresh_token,
'token_uri': credentials.token_uri,
'client_id': credentials.client_id,
'client_secret': credentials.client_secret,
'scopes': credentials.scopes}
I suggest you check the following links since they can provide more information on your issue:
Using OAuth 2.0 to Access Google APIs
Authorizing Requests to the Google Calendar API
Synchronize Resources Efficiently
For other programming languages used for the refresh token, you can check this:
Using OAuth 2.0 for Web Server Applications

OAuth 2 Authorization Code - how long is it valid?

In Webserver Grant Flow
After I obtain the Authorization Code from the authorization authority (after the user has authorized my access) how long is that code usually valid form?
The reason i am asking is, can my webserver store that code and use it in later sessions to retrieve a new access token without the need for the user to re-authenticate again? Should that be the flow?
FYI my goal is make requests from Adobe Analytics and Google Analytics on behalf of my customer. So i would want to ask my customer for authorization once until he revokes my access.
Speaking strictly of Google Oauth. There are three types of codes or tokens you should be aware of.
Authorization code
Access token
Refresh token
Authorization code is return when the user clicks accept to your application accessing their data. This code is used to exchange for an access token and a refresh token. This code can only be used once and is extremely short lived 10 minutes I believe.
Access tokens are used to access private user data. They are valid for approximately one hour.
Refresh tokens are used to gain a new access token when the access token has expired. For the most part refresh tokens do not expire however if it has not been used for six months it will no longer be valid and of course the user can always remove your access.
Answer: No storing the authentication code would be pointless. You will need to store the refresh token. make sure you are requesting offline access of your users.
I cant help you with adobe analytics however I suspect it is similar this is standard Oauth protocol we are talking about.

OAuth 2 Callback Code

I am working on a WordPress plugin that requires the use of OAuth 2. So far I've included the necessary OAuth files in an include folder in my plugin, put in the ClientId, ClientSecret I've obtained, and was able to authorize the app. After I authorized the app I received a callback code that I am supposed to use to get the token I assume. I put that code in my plugin, refreshed the page, and saw the information that is supposed to be outputted. When I go to a different page, it tells me that I am not authorized to view the information because the access token may be missing. So essentially it feels like the code that is sent to retrieve the token is only able to be used once. Do I need to store the token somehow? Any suggestions would be greatly appreciated.
In OAuth2 three-pass procedure the auth_code must be used only to obtain the access token
invoking a specific URL of the authentication server. The access token obtained can be used to access the pages later, as long as it is valid.

Resources