I am developing an application with C# on .NET Core 8 and trying to integrate Google Ads API using a service account. Despite ensuring that the Google Ads API service is enabled in my Google account, I keep receiving an “unauthorized” error message when trying to use the service.
Here is the code snippet that is causing trouble:
GoogleCredential credential = GoogleCredential.FromFile(@"C:google-keyquick-hub-421205-b36157dbaa99.json")
.CreateScoped(new[] { "https://www.googleapis.com/auth/adwords" });
if (credential.UnderlyingCredential is ITokenAccessWithHeaders tokenAccess)
{
var refreshToken = tokenAccess.GetAccessTokenForRequestAsync().Result;
Console.WriteLine("Token: " + refreshToken);
}
GoogleAdsClient client = new(new GoogleAdsConfig()
{
OAuth2Mode = OAuth2Flow.APPLICATION,
OAuth2ClientId = "102949740129148030139",
OAuth2ClientSecret = "b36153dbaa998eabdb7cf141925962f2f45c7f11",
OAuth2RefreshToken = refreshToken
});
Some points to note:
- I am using a service account and have already downloaded the JSON
file with the credentials. The Google Ads API service is activated on
my Google account. - I am not sure if the refreshToken variable in my
code actually holds the refresh token or an access token since I’m
using a service account. - I’ve already double-checked that my OAuth2
client ID and client secret are correct.
Can anyone point out what might be wrong here? I am specifically confused about whether I’m correctly using the service account to obtain the tokens and authenticate the request. Any suggestions on how to fix this unauthorized error would be greatly appreciated.