Skip to content

API access using own credentials (desktop application flow)

Anash P. Oommen edited this page Oct 28, 2020 · 2 revisions

This guide will walk you through how to setup OAuth2 for API access using your own credentials using desktop application flow. These steps only need to be done once, unless you revoke, delete, or need to change the allowed scopes for your OAuth2 credentials.

Step 1 - Creating OAuth2 credentials

Follow the steps to configure a Google API Console project for the Google Ads API, note the client ID and secret, then come back to this page.

Step 2 - Setting up the client library

Adding OAuth2 support for your application (single login)

If your application manages only one Advertiser account (or a hierarchy of Advertiser accounts all linked under a single master manager account), then you don’t need to build OAuth2 flow into your application. You can instead run the AuthenticateInDesktopApplication example as follows:

  1. Download the code examples from GitHub release.
  2. Unzip the folder and run Authentication\AuthenticateInDesktopApplication example.
  3. Follow the instructions to generate necessary configuration.

Adding OAuth2 support for your application (multiple logins)

If you manage multiple unrelated AdWords accounts, then you need to build OAuth2 sign-in flow into your application as part of adding OAuth2 support for your application.

  1. Configure the following keys in your App.config / Web.config.
<add key="AuthorizationMethod" value="OAuth2" />
<add key="OAuth2ClientId" value="INSERT_OAUTH2_CLIENT_ID_HERE" />
<add key="OAuth2ClientSecret" value="INSERT_OAUTH2_CLIENT_SECRET_HERE" />
<add key="OAuth2Mode" value="APPLICATION" />
  1. At runtime, prompt the user to authorize your application, as follows:
public class ConsoleExample {
  static void Main(string[] args) {
   GoogleAdsConfig config = new GoogleAdsConfig();
   // Load the JSON secrets.
   ClientSecrets secrets = new ClientSecrets() {
     ClientId = config.OAuth2ClientId,
     ClientSecret = config.OAuth2ClientSecret
   };

   try {
     // Authorize the user using installed application flow. This will open
     // a browser with a page for the user to authenticate against.
     Task<UserCredential> task = GoogleWebAuthorizationBroker.AuthorizeAsync(
         secrets,
         new string[] { GOOGLE_ADS_API_SCOPE },
         String.Empty,
         CancellationToken.None,
         new NullDataStore()
     );
      
     UserCredential credential = task.Result;
     
     // Store this token for future use.
     string refreshToken = credential.Token.RefreshToken;
     
     // To make a call, set the refreshtoken to the config, and
     // create the GoogleAdsClient.
     config.OAuth2RefreshToken = refreshToken;
     GoogleAdsClient client = new GoogleAdsClient(config);

    // Now use the client to create services and make API calls.
    // ...
  }
}