Google Ads

OAuth2 Authentication  |  AdWords API  |  Google Developers

All AdWords API calls must be authorized through OAuth2.
OAuth2 enables your AdWords API client app to access a user’s Google Ads account
without having to handle or store the user’s login info.

Generate OAuth2 credentials

Perform the following steps to generate OAuth2 credentials.

Determine your app type

First, determine the appropriate app type for the app you want to build.
There are two app type options for the AdWords API:

  • Installed application (recommended)
  • Web application

Check the table below to see which type is most appropriate for the app you want to build:

Choose this app type If …
Installed app (recommended)
  • You are managing all of your Google Ads accounts using a single top level manager account.
  • You’re a first-time user, or want to get started quickly with the simplest setup.
  • Your app will manage the same set of Google Ads accounts, with multiple users.
Web app
  • You want to authenticate as any user who grants permission to your app to access their Google Ads account data.
  • You want to easily generate multiple authorization credentials, to manage, for example, third party accounts.
  • Your app requires callback URLs. Callback URLs are not supported in the installed app flow.

For more details see the Google Identity Platform OAuth documentation for installed apps
and web apps.

Create a client ID and client secret

Once you’ve determined your app type, click the corresponding tab below and follow the
instructions to generate the OAuth2 client ID and client secret:

Installed app
  1. Open the Google API Console Credentials page.
  2. Click Select a project, then NEW PROJECT, and enter a name
    for the project, and optionally, edit the provided project ID. Click
    Create.
  3. On the Credentials page, select Create credentials, then
    OAuth client ID.
  4. You may be prompted to set a product name on the Consent screen; if so,
    click Configure consent screen, supply the requested information, and
    click Save to return to the Credentials screen.
  5. Select Other for the Application type, and enter any
    additional information required.
  6. Click Create.
  7. On the page that appears, copy the client ID and client
    secret
    to your clipboard, as you will need them when you configure your
    client library.

Client ID and client secret screenshot

Web app
  1. Open the Google API Console Credentials page.
  2. Click Select a project, then NEW PROJECT, and enter a name
    for the project, and optionally, edit the provided project ID. Click
    Create.
  3. On the Credentials page, select Create credentials, then
    OAuth client ID.
  4. You may be prompted to set a product name on the Consent screen; if so,
    click Configure consent screen, supply the requested information, and
    click Save to return to the Credentials screen.
  5. Select Web Application for the Application Type. Follow the
    instructions to enter JavaScript origins, redirect URIs, or both.
  6. Click Create.
  7. On the page that appears, copy the client ID and client
    secret
    to your clipboard, as you will need them when you configure your
    client library.

Client ID and client secret screenshot

Configure and use a client library

Follow the appropriate guide below to use the OAuth2 credentials in the
configuration for your language’s client library:

OAuth2 Playground

Another option for generating OAuth2 credentials is to use the OAuth2
Playground
. The OAuth2 Playground, in conjunction with the Google API Console,
allows you to manually create OAuth2 tokens.

The OAuth2 Playground is for users who only need to access the accounts for a
single manager account or Google Ads user. If you need to prompt multiple
users for credentials, then the client library-based approach described above
is likely better.

Setup

Get a client ID and client secret

  1. Open the Google API Console Credentials page.

  2. From the project drop-down, select an existing project or create a new one.

  3. On the Credentials page, select Create credentials, then select
    OAuth client ID.

  4. Under Application type, choose Web application.

  5. Under Authorized redirect URIs, add a line with:

    https://developers.google.com/oauthplayground
    
  6. Click Create.

  7. On the page that appears, take note of the client ID and client
    secret
    . You’ll need these in the next step.

Generate tokens

  1. Go to the OAuth2 Playground via this
    link
    ,
    which should pre-populate some key values for you.

  2. Click the gear icon in the
    upper right corner and check the box labeled Use your own OAuth
    credentials
    (if it isn’t already checked).

  3. Make sure that:

    • OAuth flow is set to Server-side.
    • Access type is set to Offline (this ensures you get a
      refresh token and an access token, instead of just an access token).
  4. Enter the OAuth2 client ID and OAuth2 client secret you obtained above.
    playground settings

  5. In the section labeled Step 1 – Select & authorize APIs, enter the following URL in the
    text box at the bottom, if it’s not already there, then click Authorize APIs:

    https://www.googleapis.com/auth/adwords
    

    authorize apis

  6. If prompted, log in to the account to which you want to grant access and
    authorization. Otherwise, confirm that the current Google user in the top
    right corner is the Google Ads or manager account for whom you want to obtain
    credentials.

  7. A prompt appears indicating your app would like to Manage your Google Ads Campaigns.
    Click Accept to continue.

  8. In the tab labeled Step 2 – Exchange authorization code for tokens, you
    should now see an Authorization code. Click Exchange authorization
    code for tokens
    .

    playground authcode token

  9. If all goes well, you should see the Refresh token and Access token
    filled in for you (you may have to re-expand Step 2 – Exchange
    authorization code for tokens
    to see these values):

    playground refresh token

  10. Copy the Refresh token into the configuration file for your client
    library of choice, along with the client ID and client
    secret
    . See the instructions above
    to set configuration options for your client library
    of choice.

Remove the OAuth2 Playground from your client ID

Now that you have a refresh token, you no longer need the OAuth2 Playground
to be an authorized redirect URI. To remove it from the list of authorized
redirect URIs:

  1. Go to the Google API Console Credentials page.

  2. From the project drop-down, select your project.

  3. On the Credentials page, click the client ID name to edit.

  4. Remove https://developers.google.com/oauthplayground from the Authorized
    redirect URIs
    . Note that you must leave at least one redirect URI in
    place.

  5. Click Save.

You now have the OAuth credentials you need to issue AdWords API
requests, and to try out the code samples
for your client library of choice.

OAuth2 service accounts

This section discusses how to access the AdWords API with service accounts.

A service account is an account that belongs to your application instead of
to an individual end user. Service accounts allow server-to-server interactions
between a web application and a Google service. Your application calls Google
APIs on behalf of the service account, so users aren’t directly involved.

The AdWords API allows service account access through
G Suite domains.

Service accounts employ an OAuth2 flow that doesn’t require human authorization,
but uses instead a key file that only your app can access.

Using service accounts provides two key benefits:

  • Authorization for an app to access a Google API is done as a
    configuration step, avoiding the complications associated with other
    OAuth2 flows that require user intervention, or that require your
    app to cache tokens to avoid user intervention.
  • OAuth2 assertion flow allows your app to impersonate
    other users if necessary.

An alternative to service accounts

Developers often consider using service accounts because they want
programmatic access to the API using OAuth2 without user intervention.

Because of the complexity of setting up service account access for the AdWords API,
we recommend a simpler alternative that achieves the same goal,
which is to use the OAuth2 installed application flow and persist
the refresh token. This way, your app will always be able to request a new access token when
necessary.

This process requires you to authorize your app during by configuring your client library
according to the installed app procedure
outlined above. This only needs to be done once, since Google OAuth2
refresh tokens don’t expire.

Prerequisites

  • A G Suite domain
    that you own such as mydomain.com or mybusiness.com.
  • An AdWords API developer token and optionally a test account.
  • The client library
    for the language you’re using.

Setting up service account access

First you must generate a service account key in the Google API Console:

  1. While logged in to your G Suite account, open the
    Google API Console.

  2. Click Select a project at the top of the screen, then NEW PROJECT.
    Supply the requested information and click Create. After a moment, the
    new project becomes the active project.

  3. From the menu in the upper left corner, choose IAM & admin, then select
    Service accounts.

  4. Click Create service account at the top.

  5. Enter a name for the service account.

  6. Check Furnish a new private key, and select JSON as the key type.

  7. Check Enable G Suite Domain-wide Delegation, and enter a product name
    for the consent screen.

  8. Click Create. The JSON key file is downloaded to your machine. Store it
    in a safe place that only you can access.

  9. The new service account is shown on the Service Accounts page for the
    project.

Security concerns

Because of G Suite’s domain-level control, it’s important to protect the key
file that allows a service account to access the Google services for which it’s
authorized. This is especially true since that service account will have the
ability to impersonate any user in the domain.

Another good practice is to allow service accounts to access only one Google
API each (using the scope field described in the following section). This
is a preemptive measure to limit the amount of data an attacker can access if
the service account’s key file
is compromised.

Granting impersonation abilities

Perform the following steps to grant impersonation abilities to a service
account:

  1. Add a new authorized API client to your G Suite domain by going
    to:

    https://admin.google.com/YOUR_DOMAIN/ManageOauthClients
    
  2. Add a new authorized API client as the Client Name, using the client
    ID
    from the JSON file you generated when you enabled the service account
    for domain-wide delegation in the steps
    above
    .

  3. Enter the following for the API scope:

    https://www.googleapis.com/auth/adwords
    
  4. Repeat the process for all other service accounts to which you want to grant
    impersonation power.

You can now use the service account to access your Google Ads account via the
OAuth2 assertion flow.

Configuring your client library

Select your language below for instructions to configure your client library.

Optimizing OAuth2 requests

If your app doesn’t share credentials across servers, processes, and threads,
it may be sending an excessive number of requests to Google. This can cause our
servers to enforce rate limits on your app, resulting in performance
degradation.

This section explains how to optimize OAuth2 credential management so your app
can efficiently interact with the AdWords API.

Credential sharing strategies

Sharing credentials across your API requests improves performance and avoids
excessive overhead that can result in rate limit errors.

Your credential sharing strategy depends on your app’s design:

In multithreaded apps, you should supply each thread’s session with the same
credential.

In multiprocess or distributed apps, you must implement some infrastructure to
share the credential across processes. You should also ensure that threads
aren’t blocked, and that race conditions aren’t present in your implementation.

An app that is both multiprocess / distributed and multithreaded within each
process should use both strategies.

These strategies are described below for authenticating a single Google Ads
account, such as the top-level manager account in your hierarchy.

Adapting these strategies to authenticate for multiple Google Ads
accounts
is described after.

Multithreaded apps

In multithreaded apps, the credential should be shared between threads.
Refreshing of the credential should be performed synchronously to avoid a race
condition.

runtime

The diagram shows a runtime with threads drawing from a pool of sessions (or
users) to make requests to the AdWords API. Note that each session should use
the same credential object. On each API request, the thread obtains a session
(or user). If the credential requires an access token refresh, it must be done
synchronously—that is, the credential object must be thread-safe—to
avoid a race condition.

The client libraries make sharing a credential across threads straightforward.
Each client library has a session (or user) object with a credential that it
reuses throughout its lifetime. To share the credential across threads, simply
construct each session using the same credential. In all client libraries, the
credential is a thread-safe object that refreshes itself synchronously when its
access token expires.

For example, in the Java client library, you would create a Credential as a
singleton and share it across all sessions.

Multiprocess or distributed apps

In multiprocess or distributed apps, sharing the credential requires you to
persist it. To ensure multiple processes or servers don’t attempt to refresh
the credential at the same time (resulting in excessive refresh requests), we
advise proactively refreshing the credential in a central place and sharing it
across processes/servers.

For example, a separate job or service can be responsible for periodically
refreshing the credential, and proactively pushing it to the data store for use
by the pool of servers.

refresh

The diagram shows the credential refresh job running periodically and writing
the credential’s properties to the data store. Each server then retrieves the
credential before making a request to the API.

Refresh job

The refresh job periodically refreshes the credential and stores it in
the data store. The job shouldn’t wait until the current credential expires
before initiating a refresh: Doing so would open a window when the app is
stalled for lack of a valid credential.

A better alternative is to force the refresh periodically, each time replacing
the credential in the data store with the new one. The refresh job should run
well before the current credential expires to allow some time in case of a
transient failure. Every 15 minutes is a good starting point.

Data store

A central data store can be used to share the credential between processes and
servers.

You can make use of an existing data store or deploy one specific to the sharing
of credentials between servers. Solutions include caching servers (such as
Memcached or Infinispan), or
NoSQL data stores (such as MongoDB).

The data store must provide a reliable interface to all the servers making
requests to the API. It should be optimized for fast reading operations,
since the server or process will read the current credential more frequently than
the refresh job will update it.

Keep in mind that credentials must be stored
securely
.

When storing the credential, you should store the calculated expiry_time
(now + expires_in) and refresh_token
alongside the access_token. The expiry_time is calculated as the time of the
access_token refresh request plus the expires_in time.

Server pool

Each server or process in the pool retrieves the latest credential from the
data store before making a request. As long as the refresh job is running
successfully, the credential will be valid. But if the refresh job or
data store fails, you should have a fallback mechanism.

If a server or process cannot get a credential from the data
store, or if the credential is expired, the server should refresh its own
credentials to allow the app to continue working with the API
until the problem is resolved.

In processes with multiple threads, you should use the same sharing strategy
described above to share the credential across threads.

Authenticating multiple accounts

A credential generated for an Google Ads manager account can be used to access all
its child accounts. Thus, for users with a single manager
account hierarchy, it’s usually sufficient to generate a credential for the
top-level manager account, thereby authorizing the app for all
the Google Ads accounts beneath it.

In other cases, your app must access Google Ads accounts that are not
related to one another in any manager account hierarchy. In this case, you should
generate and maintain different credentials for different accounts, such
as for each Google Ads client account you access, or each top-level manager account
in the independent hierarchies you access.

You can follow the same strategies for multithreaded
and multiprocess / distributed
apps with minor modification. When using a shared data store,
credentials must be indexed by the account identifier customerId to
ensure credentials are associated with the right account.
Additionally, the refresh job should keep all credentials
refreshed. If a new account is linked, the refresh job may need to be triggered.

Finally, in multithreaded apps, you should only share the credential object
across threads that are operating on the account with which the credential object
is associated.

OAuth2 internals

Our client libraries automatically take
care of the details covered below, so read on only if you’re interested in
what’s happening behind the scenes, or if you’re not using one of our
client libraries.

This section is intended for advanced users who are already familiar
with the OAuth 2.0 specification and
know how to use OAuth2 with Google APIs.

Scope

A single access token can grant varying degrees of access to multiple APIs. A
variable parameter called scope controls the set of resources and operations
that an access token permits. During the access token request, your app
sends one or more values in the scope parameter.

The present and deprecated scopes for the AdWords API:

Scope Meaning
https://www.googleapis.com/auth/adwords Read/write access to AdWords API.

https://adwords.google.com/api/adwords/
This scope is deprecated and should no longer be used to obtain future authorizations.
Previously authorized tokens will continue to work.

Offline access

It’s common for an AdWords API client app to request offline access.
For example, your app may want to run batch jobs when
your user is not physically online browsing your website.

To request offline access for a web application type, make sure you set the
access_type parameter to offline. You can find additional information in
Google’s OAuth2
guide
.

For installed application type, offline access is enabled by default – you
don’t have to explicitly request it.

The HTTP header in every request to the AdWords API server must include the
access token in this form:

Authorization: Bearer THE_ACCESS_TOKEN

For example:

POST … HTTP/1.1
Host: …
Authorization: Bearer 1/fFAGRNJru1FTz70BzhT3Zg
Content-Type: text/xml;charset=UTF-8
Content-Length: …



Access and refresh token

In most cases, you need to store the refresh token securely for future use.
To learn more about how to request access and refresh tokens, read the guide corresponding to your
application type:

Access token expiration

An access token has an expiration time (based on the
expires_in value) after
which the token is no longer valid. You can use the refresh token to refresh
an expired access token. By default, our client libraries automatically
refresh expired access tokens.

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button
Close