Search code examples
c#google-apigoogle-oauthgoogle-ads-apigoogle-api-dotnet-client

Google OAuth Refresh Token Auto Update


I have a project whose Publishing status is Testing (I am using Google Ads Api).

            using FileStream stream = new("Credentials.json", FileMode.Open, FileAccess.Read);

            // The file token.json stores the user's access and refresh tokens, and is created
            // automatically when the authorization flow completes for the first time.

            UserCredential credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
             GoogleClientSecrets.FromStream(stream).Secrets,
             scopes,
             "user",
             CancellationToken.None,
             new FileDataStore("Token", true)
            );

            if (credential.Token.IsExpired(credential.Flow.Clock))
                await credential.RefreshTokenAsync(CancellationToken.None);

When I use the code above, it expects me to log in via Gmail, but I want to automatically handle the Refresh token and continue uninterrupted requests without understanding anything to the user. I am using Desktop Application as Flow, but I am using Net 5 Api as Framework. I look forward to your help in this matter.

Thank you from now.


Solution

  • The issue you are having is not with your code the issue is that your app is still in the testing phase.

    If you check the docs for oauth2#expiration you will find it says

    A Google Cloud Platform project with an OAuth consent screen configured for an external user type and a publishing status of "Testing" is issued a refresh token expiring in 7 days.

    Solution is to set your app to production then your refresh tokens will no longer expire.

    enter image description here

    Not sure why you are sending a curl request to get new refresh tokens. This can all be done with the code you have.