Missing refresh_token error even though it's there

1,338 views
Skip to first unread message

Henrik Ravnskjær

unread,
Jun 26, 2023, 10:28:46 AM6/26/23
to Google Ads API and AdWords API Forum
First off. I'm really new to Google Ads API.

I'm trying to created a small C# console app to retrieve some basic ads info (clicks, impressions..)

I have created a cloud app to get a client ID and secret. Enabled Google Ad API.
I have the developer token from Google Ads API Center.
(It is still in Test Access level. I have applied for basic access, but waiting on approval)

Then I needed to get a refresh token for my user. I used a tutorial program to get that, so now (I think) I have all the GoogleAdsAPI info that I added to app.config.
<GoogleAdsApi>
  <add key="DeveloperToken" value="0ZkDzlCf7...removed..."/>
  <add key = 'OAuth2Mode' value = 'APPLICATION' />
  <add key = 'OAuth2ClientId' value = '75347...removed...apps.googleusercontent.com' />
  <add key = 'OAuth2ClientSecret' value = 'GOCSPX-o...removed...' />
  <add key = 'OAuth2RefreshToken' value = '1//0chFAQh_a-BDWCg...removed...' />
  <add key = 'LoginCustomerId' value = '9434...removed...' />
</GoogleAdsApi>

I then have this code I try to run:
      GoogleAdsServiceClient googleAdsService = client.GetService(Services.V14.GoogleAdsService);

      string query =
                 @"SELECT
                 ad_group.id,
                 ad_group.name,
                 campaign.id,
                 campaign.name,
                 metrics.impressions,
                 metrics.clicks,
                 segments.device,
                 segments.day,
             FROM ad_group
             WHERE segments.date DURING LAST_7_DAYS
                 AND ad_group.status IN ('ENABLED','PAUSED')
             ORDER BY metrics.impressions DESC
             LIMIT 50";
      try
      {
        // Issue a search request.
        googleAdsService.SearchStream(customerId.ToString(), query,
            delegate (SearchGoogleAdsStreamResponse resp)
            {
              // Display the results.
              foreach (GoogleAdsRow criterionRow in resp.Results)
              {
                Console.WriteLine(
                            $"'{criterionRow.AdGroup.Name}' with ID " +
                            $"{criterionRow.AdGroup.Id} in campaign " +
                            $"'{criterionRow.Campaign.Name}' with ID " +
                            $"{criterionRow.Campaign.Id} had " +
                            $"{criterionRow.Metrics.Impressions.ToString()} impressions, " +
                            $"{criterionRow.Metrics.Clicks} clicks " +
                            "during the last 7 days.");
              }
            }
        );
      }
      catch (GoogleAdsException e)
      {
        Console.WriteLine("Failure:");
        Console.WriteLine($"Message: {e.Message}");
        Console.WriteLine($"Failure: {e.Failure}");
        Console.WriteLine($"Request ID: {e.RequestId}");
        throw;
      }

But I get this error:
System.AggregateException: 'One or more errors occurred. (Status(StatusCode="Internal", Detail="Error starting gRPC call. TokenResponseException: Error:"invalid_request", Description:"Missing required parameter: refresh_token", Uri:""", DebugException="Google.Apis.Auth.OAuth2.Responses.TokenResponseException: Error:"invalid_request", Description:"Missing required parameter: refresh_token", Uri:""
   at Google.Apis.Auth.OAuth2.Responses.TokenResponse.FromHttpResponseAsync(HttpResponseMessage response, IClock clock, ILogger logger)
   at Google.Apis.Auth.OAuth2.Requests.TokenRequestExtenstions.ExecuteAsync(TokenRequest request, HttpClient httpClient, String tokenServerUrl, CancellationToken taskCancellationToken, IClock clock, ILogger logger)
   at Google.Apis.Auth.OAuth2.Flows.AuthorizationCodeFlow.FetchTokenAsync(String userId, TokenRequest request, CancellationToken taskCancellationToken)
   at Google.Apis.Auth.OAuth2.Flows.AuthorizationCodeFlow.FetchTokenAsync(String userId, TokenRequest request, CancellationToken taskCancellationToken)
   at Google.Apis.Auth.OAuth2.Flows.AuthorizationCodeFlow.RefreshTokenAsync(String userId, String refreshToken, CancellationToken taskCancellationToken)
   at Google.Apis.Auth.OAuth2.UserCredential.RefreshTokenAsync(CancellationToken taskCancellationToken)
   at Google.Apis.Auth.OAuth2.TokenRefreshManager.RefreshTokenAsync()
   at Google.Apis.Auth.OAuth2.UserCredential.GetAccessTokenWithHeadersForRequestAsync(String authUri, CancellationToken cancellationToken)
   at Google.Apis.Auth.OAuth2.TokenRefreshManager.<GetAccessTokenForRequestAsync>g__LogException|10_0(Task task)
   at Grpc.Auth.GoogleAuthInterceptors.<>c__DisplayClass3_0.<<FromCredential>b__0>d.MoveNext()
--- End of stack trace from previous location ---
   at Grpc.Net.Client.Internal.GrpcProtocolHelpers.ReadCredentialMetadata(DefaultCallCredentialsConfigurator configurator, GrpcChannel channel, HttpRequestMessage message, IMethod method, CallCredentials credentials)
   at Grpc.Net.Client.Internal.GrpcCall`2.ReadCredentials(HttpRequestMessage request)
   at Grpc.Net.Client.Internal.GrpcCall`2.RunCall(HttpRequestMessage request, Nullable`1 timeout)"))'

It says the refresh token isn't there... But it is in my config file...
What I'm I missing/doing wrong??

Google Ads API Forum Advisor

unread,
Jun 27, 2023, 8:39:28 AM6/27/23
to h...@feline.dk, adwor...@googlegroups.com

Hi,

Thank you for raising your concern to the Google Ads API team.

I understand you are encountering errors with your refresh token. With that being said, kindly refer to this document:(https://developers.google.com/google-ads/api/docs/first-call/refresh-token#c) or here:(https://developers.google.com/google-ads/api/docs/client-libs/dotnet/oauth-web) for the steps as well as the setup of your app.config file. More information about configuration for your client library can also be found here: https://developers.google.com/google-ads/api/docs/client-libs/dotnet/configuration

If you still encounter the issue, kindly raise your concern to the author of the client library you are using by creating a new issue - https://github.com/googleads/google-ads-dotnet/issues

Let me know if you have any questions.
 

This message is in relation to case "ref:_00D1U1174p._5004Q2mXaSe:ref"

Thanks,
 
Google Logo Google Ads API Team


Henrik Ravnskjær

unread,
Jun 28, 2023, 6:53:15 AM6/28/23
to Google Ads API and AdWords API Forum
Instead of using app.config I changed the code to include a config when I create the client.
    GoogleAdsConfig config = new GoogleAdsConfig()
    {
      OAuth2Mode = Google.Ads.Gax.Config.OAuth2Flow.APPLICATION,
      OAuth2ClientId = ClientId,
      OAuth2ClientSecret = ClientSecret,
      OAuth2RefreshToken = RefreshToken,
      LoginCustomerId = CustomerID,
      DeveloperToken = DeveloperToken
    };
    var client = new GoogleAdsClient(config);

That works, But...

Now I get a Permission Denied:
{"Status(StatusCode=\"PermissionDenied\", Detail=\"The caller does not have permission\")"}

I used my google ads manager account to generate the refresh token. 
The same manager I use to login to google ads and can see all our campaigns (and the Ads API center where I got the developer token). So I know that user have access.

Any idea why that user doesn't have permission?
It it another kind of permission I'm missing some where??

Google Ads API Forum Advisor

unread,
Jun 29, 2023, 2:51:00 PM6/29/23
to h...@feline.dk, adwor...@googlegroups.com

Hi Henrik, 

Thanks for reaching out to the Google Ads API Team. I hope you are doing well today.

With regard to your concern, it appears that you've encountered the USER_PERMISSION_DENIED error which occurs when the authorized customer does not have access to the operating customer.

This is an authorization error (https://developers.google.com/google-ads/api/docs/best-practices/common-errors#authorizationerror) and its common cause is when authenticating as a user with access to a manager account but not specifying login-customer-id in the request. It also occurs when the OAuth2 credentials (https://developers.google.com/google-ads/api/docs/oauth/cloud-project) you are using were generated by a user / email address that does not have access (https://support.google.com/google-ads/answer/9978556?visit_id=638028230738600037-122357065&rd=1) to the account (customer_id) specified in your request. You can manage user access by referring to this article (https://support.google.com/google-ads/answer/6372672).

If the issue persists even after doing the above details, for our team to further compare, investigate, and validate why you are encountering issues, can you provide more information?

  • Provide the complete (request and response with request-id) logs with request ID generated as shown in the respective links.
  • Email address of the authenticating user

You may send these to us via Reply privately to author option. If you haven't enabled logging yet, it can be enabled by navigating to the Client libraries > Your client library (ex. Java) > Logging documentation, which you can access from this link. 

Reference links:

Have a great day.

Reply all
Reply to author
Forward
0 new messages