Java
// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.ads.googleads.examples.authentication;
import com.google.ads.googleads.lib.GoogleAdsClient;
import com.google.ads.googleads.lib.GoogleAdsClient.Builder.ConfigPropertyKey;
import com.google.auth.oauth2.ClientId;
import com.google.auth.oauth2.UserAuthorizer;
import com.google.auth.oauth2.UserCredentials;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import java.io.BufferedReader;
import java.io.Console;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URL;
import java.util.Properties;
/**
* Creates an OAuth2 refresh token for the Google Ads API using the Desktop application flow.
*
* <p>This example is meant to be run from the command line and requires user input.
*/
public class AuthenticateInDesktopApplication {
// Scopes for the generated OAuth2 credentials. The list here only contains the AdWords scope,
// but you can add multiple scopes if you want to use the credentials for other Google APIs.
private static final ImmutableList<String> SCOPES =
ImmutableList.<String>builder().add("https://www.googleapis.com/auth/adwords").build();
private static final String CALLBACK_URI = "urn:ietf:wg:oauth:2.0:oob";
public static void main(String[] args) throws IOException {
// Generates the client ID and client secret from the Google Cloud Console:
// https://console.cloud.google.com
String clientId;
String clientSecret;
Console console = System.console();
if (console == null) {
// The console will be null when running this example in some IDEs. In this case, please
// set the clientId and clientSecret in the lines below.
clientId = "INSERT_CLIENT_ID_HERE";
clientSecret = "INSERT_CLIENT_SECRET_HERE";
// Ensures that the client ID and client secret are not the "INSERT_..._HERE" values.
Preconditions.checkArgument(
!clientId.matches("INSERT_.*_HERE"),
"Client ID is invalid. Please update the example and try again.");
Preconditions.checkArgument(
!clientSecret.matches("INSERT_.*_HERE"),
"Client secret is invalid. Please update the example and try again.");
} else {
console.printf(
"NOTE: When prompting for the client secret below, echoing will be disabled%n");
console.printf(" since the client secret is sensitive information.%n");
console.printf("Enter your client ID:%n");
clientId = console.readLine();
console.printf("Enter your client secret:%n");
clientSecret = String.valueOf(console.readPassword());
}
new AuthenticateInDesktopApplication().runExample(clientId, clientSecret);
}
public void runExample(String clientId, String clientSecret) throws IOException {
UserAuthorizer userAuthorizer =
UserAuthorizer.newBuilder()
.setClientId(ClientId.of(clientId, clientSecret))
.setScopes(SCOPES)
.setCallbackUri(URI.create(CALLBACK_URI))
.build();
URL authorizationUrl = userAuthorizer.getAuthorizationUrl(null, null, null);
System.out.printf("Paste this url in your browser:%n%s%n", authorizationUrl);
// Waits for the authorization code.
System.out.println("Type the code you received here: ");
@SuppressWarnings("DefaultCharset") // Reading from stdin, so default charset is appropriate.
String authorizationCode = new BufferedReader(new InputStreamReader(System.in)).readLine();
// Exchanges the authorization code for credentials and print the refresh token.
UserCredentials userCredentials =
userAuthorizer.getCredentialsFromCode(authorizationCode, null);
System.out.printf("Your refresh token is: %s%n", userCredentials.getRefreshToken());
// Prints the configuration file contents.
Properties adsProperties = new Properties();
adsProperties.put(ConfigPropertyKey.CLIENT_ID.getPropertyKey(), clientId);
adsProperties.put(ConfigPropertyKey.CLIENT_SECRET.getPropertyKey(), clientSecret);
adsProperties.put(
ConfigPropertyKey.REFRESH_TOKEN.getPropertyKey(), userCredentials.getRefreshToken());
adsProperties.put(
ConfigPropertyKey.DEVELOPER_TOKEN.getPropertyKey(), "INSERT_DEVELOPER_TOKEN_HERE");
showConfigurationFile(adsProperties);
}
private void showConfigurationFile(Properties adsProperties) throws IOException {
System.out.printf(
"Copy the text below into a file named %s in your home directory, and replace "
+ "INSERT_XXX_HERE with your configuration:%n",
GoogleAdsClient.Builder.DEFAULT_PROPERTIES_CONFIG_FILE_NAME);
System.out.println(
"######################## Configuration file start ########################");
adsProperties.store(System.out, null);
System.out.printf(
"# Required for manager accounts only: Specify the login customer ID used to%n"
+ "# authenticate API calls. This will be the customer ID of the authenticated%n"
+ "# manager account. You can also specify this later in code if your application%n"
+ "# uses multiple manager account + OAuth pairs.%n"
+ "#%n");
System.out.println(
"# " + ConfigPropertyKey.LOGIN_CUSTOMER_ID.getPropertyKey() + "=INSERT_LOGIN_CUSTOMER_ID");
System.out.println(
"######################## Configuration file end ##########################");
}
}
C#
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using Google.Apis.Auth.OAuth2;
using Google.Apis.Util.Store;
using System;
using System.Threading;
using System.Threading.Tasks;
namespace Google.Ads.GoogleAds.Examples
{
/// <summary>
/// Entry point for the application.
/// </summary>
internal class Program
{
/// <summary>
/// The Google Ads API scope.
/// </summary>
private const string GOOGLE_ADS_API_SCOPE = "https://www.googleapis.com/auth/adwords";
/// <summary>
/// The main entry point for the application.
/// </summary>
public static void Main(string[] args)
{
Console.WriteLine("This application generates an OAuth2 refresh token for use with " +
"the Google Ads API .NET client library. To use this application\n" +
"1) Follow the instructions on " +
"https://developers.google.com/google-ads/api/docs/oauth/cloud-project " +
"to generate a new client ID and secret.\n" +
"2) Enter the client ID and client Secret when prompted.\n" +
"3) Once the output is generated, copy its contents into your App.config " +
"file.\n\n");
Console.WriteLine("Important note: The client ID you use with the example should be " +
"of type 'Other'. If you are using a Web application client, you should add " +
"'http://127.0.0.1/authorize' and 'http://localhost/authorize' to the list of " +
"Authorized redirect URIs in your Google Developer Console to avoid getting a " +
"redirect_uri_mismatch error.\n\n");
// Accept the client ID from user.
Console.Write("Enter the client ID: ");
string clientId = Console.ReadLine();
// Accept the client ID from user.
Console.Write("Enter the client secret: ");
string clientSecret = Console.ReadLine();
// Load the JSON secrets.
ClientSecrets secrets = new ClientSecrets()
{
ClientId = clientId,
ClientSecret = clientSecret
};
try
{
// Authorize the user using desktop flow.
Task<UserCredential> task = GoogleWebAuthorizationBroker.AuthorizeAsync(
secrets,
new string[] { GOOGLE_ADS_API_SCOPE },
String.Empty,
CancellationToken.None,
new NullDataStore()
);
UserCredential credential = task.Result;
Console.WriteLine("\nCopy the following content into your App.config file.\n\n" +
$"<add key = 'OAuth2Mode' value = 'APPLICATION' />\n" +
$"<add key = 'OAuth2ClientId' value = '{clientId}' />\n" +
$"<add key = 'OAuth2ClientSecret' value = '{clientSecret}' />\n" +
$"<add key = 'OAuth2RefreshToken' value = " +
$"'{credential.Token.RefreshToken}' />\n");
Console.WriteLine("/n" +
"<!-- Required for manager accounts only: Specify the login customer -->\n" +
"<!-- ID used to authenticate API calls. This will be the customer ID -->\n" +
"<!-- of the authenticated manager account. It should be set without -->\n" +
"<!-- dashes, for example: 1234567890 instead of 123-456-7890. You can -->\n" +
"<!-- also specify this later in code if your application uses -->\n" +
"<!-- multiple manager account OAuth pairs. -->\n" +
"<add key = 'LoginCustomerId' value = INSERT_LOGIN_CUSTOMER_ID_HERE />/n/n");
Console.WriteLine("Press <Enter> to continue...");
Console.ReadLine();
}
catch (AggregateException)
{
Console.WriteLine("An error occured while authorizing the user.");
}
}
}
}
PHP
<?php
/*
* Copyright 2018 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Google\AdsApi\Examples\Authentication;
require __DIR__ . '/../../vendor/autoload.php';
use Google\Auth\CredentialsLoader;
use Google\Auth\OAuth2;
/**
* This example will create an OAuth2 refresh token for the Google Ads API
* using the Desktop application flow. You can then use this refresh token
* to generate access tokens to authenticate against the Google Ads API you're
* using.
*
* <p>This example is meant to be run from the command line and requires user
* input.
*/
class AuthenticateInDesktopApplication
{
/**
* @var string the OAuth2 scope for the Google Ads API
* @see https://developers.google.com/google-ads/api/docs/oauth/internals#scope
*/
private const SCOPE = 'https://www.googleapis.com/auth/adwords';
/**
* @var string the Google OAuth2 authorization URI for OAuth2 requests
* @see https://developers.google.com/identity/protocols/oauth2/native-app#step-2:-send-a-request-to-googles-oauth-2.0-server
*/
private const AUTHORIZATION_URI = 'https://accounts.google.com/o/oauth2/v2/auth';
/**
* @var string the redirect URI for OAuth2 Desktop application flows
* @see https://developers.google.com/identity/protocols/oauth2/native-app#request-parameter-redirect_uri
*/
private const REDIRECT_URI = 'urn:ietf:wg:oauth:2.0:oob';
public static function main()
{
$stdin = fopen('php://stdin', 'r');
print 'Enter your OAuth2 client ID here: ';
$clientId = trim(fgets($stdin));
print 'Enter your OAuth2 client secret here: ';
$clientSecret = trim(fgets($stdin));
print '[OPTIONAL] enter any additional OAuth2 scopes as a space '
. 'delimited string here (the Google Ads API scope is already included): ';
$scopes = self::SCOPE . ' ' . trim(fgets($stdin));
$oauth2 = new OAuth2(
[
'authorizationUri' => self::AUTHORIZATION_URI,
'redirectUri' => self::REDIRECT_URI,
'tokenCredentialUri' => CredentialsLoader::TOKEN_CREDENTIAL_URI,
'clientId' => $clientId,
'clientSecret' => $clientSecret,
'scope' => $scopes
]
);
printf(
'Log into the Google account you use for Google Ads and visit the following URL:'
. '%1$s%2$s%1$s%1$s',
PHP_EOL,
$oauth2->buildFullAuthorizationUri()
);
print 'After approving the application, enter the authorization code here: ';
$code = trim(fgets($stdin));
fclose($stdin);
print PHP_EOL;
$oauth2->setCode($code);
$authToken = $oauth2->fetchAuthToken();
print "Your refresh token is: {$authToken['refresh_token']}" . PHP_EOL . PHP_EOL;
$propertiesToCopy = '[GOOGLE_ADS]' . PHP_EOL;
$propertiesToCopy .= 'developerToken = "INSERT_DEVELOPER_TOKEN_HERE"' . PHP_EOL;
$propertiesToCopy .= <<<EOD
; Required for manager accounts only: Specify the login customer ID used to authenticate API calls.
; This will be the customer ID of the authenticated manager account. You can also specify this later
; in code if your application uses multiple manager account + OAuth pairs.
; loginCustomerId = "INSERT_LOGIN_CUSTOMER_ID_HERE"
EOD;
$propertiesToCopy .= PHP_EOL . '[OAUTH2]' . PHP_EOL;
$propertiesToCopy .= "clientId = \"$clientId\"" . PHP_EOL;
$propertiesToCopy .= "clientSecret = \"$clientSecret\"" . PHP_EOL;
$propertiesToCopy .= "refreshToken = \"{$authToken['refresh_token']}\"" . PHP_EOL;
print 'Copy the text below into a file named "google_ads_php.ini" in your home '
. 'directory, and replace "INSERT_DEVELOPER_TOKEN_HERE" with your developer '
. 'token:' . PHP_EOL;
print PHP_EOL . $propertiesToCopy;
}
}
AuthenticateInDesktopApplication::main();
Python
#!/usr/bin/env python
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""This example creates an OAuth 2.0 refresh token for the Google Ads API.
This illustrates how to step through the OAuth 2.0 native / installed
application flow.
It is intended to be run from the command line and requires user input.
"""
import argparse
from google_auth_oauthlib.flow import InstalledAppFlow
SCOPE = "https://www.googleapis.com/auth/adwords"
def main(client_secrets_path, scopes):
flow = InstalledAppFlow.from_client_secrets_file(
client_secrets_path, scopes=scopes
)
flow.run_console()
print("Access token: %s" % flow.credentials.token)
print("Refresh token: %s" % flow.credentials.refresh_token)
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="Generates OAuth 2.0 credentials with the specified "
"client secrets file."
)
# The following argument(s) should be provided to run the example.
parser.add_argument(
"--client_secrets_path",
required=True,
help=(
"Path to the client secrets JSON file from the "
"Google Developers Console that contains your "
"client ID and client secret."
),
)
parser.add_argument(
"--additional_scopes",
default=None,
help=(
"Additional scopes to apply when generating the "
"refresh token. Each scope should be separated "
"by a comma."
),
)
args = parser.parse_args()
configured_scopes = [SCOPE]
if args.additional_scopes:
configured_scopes.extend(
args.additional_scopes.replace(" ", "").split(",")
)
main(args.client_secrets_path, configured_scopes)
Ruby
#!/usr/bin/env ruby
# Encoding: utf-8
#
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# This example will create an OAuth2 refresh token for the Google Ads API using
# the Native/Installed application flow.
#
# This example is meant to be run from the command line and requires user input.
require 'googleauth'
require 'optparse'
def authenticate_in_desktop_application(client_id, client_secret)
client_id = Google::Auth::ClientId.new(client_id, client_secret)
# This example does not store credentials, so no TokenStore is needed.
user_authorizer = Google::Auth::UserAuthorizer.new(
client_id, SCOPE, nil, CALLBACK_URI)
authorization_url = user_authorizer.get_authorization_url()
printf("Paste this url in your browser:\n%s\n", authorization_url)
printf("Type the code you received here: ")
authorization_code = gets.chomp
user_credentials =
user_authorizer.get_credentials_from_code(code: authorization_code)
printf("Your refresh token is: %s\n", user_credentials.refresh_token)
printf("Copy your refresh token above into your google_ads_config.rb in your "\
"home directory or use it when instantiating the library.\n")
end
if __FILE__ == $PROGRAM_NAME
CALLBACK_URI = 'urn:ietf:wg:oauth:2.0:oob'
SCOPE = 'https://www.googleapis.com/auth/adwords'
options = {}
# The following parameter(s) should be provided to run the example. You can
# either specify these by changing the INSERT_XXX_ID_HERE values below, or on
# the command line.
#
# Parameters passed on the command line will override any parameters set in
# code.
#
# Running the example with -h will print the command line usage.
options[:client_id] = 'INSERT_CLIENT_ID_HERE'
options[:client_secret] = 'INSERT_CLIENT_SECRET_HERE'
OptionParser.new do |opts|
opts.banner = sprintf('Usage: %s [options]', File.basename(__FILE__))
opts.separator ''
opts.separator 'Options:'
opts.on('-I', '--client-id CLIENT-ID', String, 'Client ID') do |v|
options[:client_id] = v
end
opts.on('-S', '--client-secret CLIENT-SECRET', String,
'Client Secret') do |v|
options[:client_secret] = v
end
opts.separator ''
opts.separator 'Help:'
opts.on_tail('-h', '--help', 'Show this message') do
puts opts
exit
end
end.parse!
authenticate_in_desktop_application(options[:client_id],
options[:client_secret])
end
Perl
#!/usr/bin/perl -w
#
# Copyright 2019, Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# This example will create an OAuth2 refresh token for the Google Ads API using
# the Desktop application flow.
#
# This example is meant to be run from the command line and requires user input.
use strict;
use warnings;
use utf8;
use FindBin qw($Bin);
use lib "$Bin/../../lib";
use Google::Ads::GoogleAds::Client;
use Google::Ads::GoogleAds::Utils::GoogleAdsHelper;
use Getopt::Long qw(:config auto_help);
use Pod::Usage;
use Cwd qw(abs_path);
# The following parameter(s) should be provided to run the example. You can
# either specify these by changing the INSERT_XXX_ID_HERE values below, or on
# the command line.
#
# Parameters passed on the command line will override any parameters set in
# code.
#
# Running the example with -h will print the command line usage.
my $client_id = "INSERT_CLIENT_ID_HERE";
my $client_secret = "INSERT_CLIENT_SECRET_HERE";
my $additional_scopes = "INSERT_ADDITIONAL_SCOPES_HERE";
sub authenticate_in_desktop_application {
my ($api_client, $client_id, $client_secret, $additional_scopes) = @_;
my $auth_handler = $api_client->get_oauth_2_handler();
$auth_handler->set_client_id($client_id);
$auth_handler->set_client_secret($client_secret);
$auth_handler->set_additional_scopes($additional_scopes)
if check_params($additional_scopes);
# Open a browser and point it to the authorization URL, authorize the access
# and then enter the generated authorization code.
print
"\nPaste this url in your browser:\n",
$auth_handler->get_authorization_url(), "\n\n";
# Wait for the authorization code.
print "Type the authorization code you received here: ";
my $code = <STDIN>;
$code = trim($code);
# Request the access token using the authorization code, so it can be used
# to access the API.
if (my $error = $auth_handler->issue_access_token($code)) {
die($error);
}
# After the access token and refresh token are generated, you should store the
# refresh token and reuse it for future calls, by either changing your
# googleads.properties file or setting in the authorization handler as follows:
#
# $api_client->get_oauth_2_handler()->set_client_id($client_id);
# $api_client->get_oauth_2_handler()->set_client_secret($client_secret);
# $api_client->get_oauth_2_handler()->set_refresh_token($refresh_token);
printf
"\nReplace the following keys and values in your googleads.properties " .
"configuration file:\n\n" .
"clientId=%s\n" . "clientSecret=%s\n" . "refreshToken=%s\n\n",
$client_id, $client_secret,
$auth_handler->get_refresh_token();
return 1;
}
# Don't run the example if the file is being included.
if (abs_path($0) ne abs_path(__FILE__)) {
return 1;
}
# Get Google Ads Client with the default API version.
my $api_client = Google::Ads::GoogleAds::Client->new();
# Parameters passed on the command line will override any parameters set in code.
GetOptions(
'client_id=s' => \$client_id,
'client_secret=s' => \$client_secret,
'additional_scopes=s' => \$additional_scopes
);
# Print the help message if the parameters are not initialized in the code nor
# in the command line.
pod2usage(2) if not check_params($client_id, $client_secret);
# Call the example.
authenticate_in_desktop_application($api_client, $client_id, $client_secret,
$additional_scopes);
=pod
=head1 NAME
authenticate_in_desktop_application
=head1 DESCRIPTION
This example will create an OAuth2 refresh token for the Google Ads API using the
Desktop application flow.
=head1 SYNOPSIS
authenticate_in_desktop_application.pl [options]
-help Show the help message.
-client_id The OAuth2 client id.
-client_secret The OAuth2 client secret
-additional_scopes [optional] Additional OAuth2 scopes seperated by comma.
=cut