Similar to the service account workflow , the single user authentication flow makes use of the authorization and user management features offered by the Google Ads UI to grant the app access to all the necessary accounts. This authentication workflow has two steps:
- Вы предоставляете одному пользователю доступ ко всем аккаунтам Google Ads , которые должны управляться приложением.
- Пользователь разрешает вашему приложению управлять его аккаунтами Google Ads от его имени, предоставляя таким образом приложению доступ ко всем аккаунтам Google Ads.
Поскольку задействован только один пользователь, вы можете использовать такие инструменты, как gcloud CLI или пример кода GenerateUserCredential, вместо того, чтобы создавать собственный процесс аутентификации пользователей OAuth 2.0.
A related use case for this workflow is when your accounts can be accessed through a handful of user logins (for example, 3-4 users), so the development effort to build a full-blown OAuth user authentication workflow isn't justified when compared to the effort for obtaining authorization for 3-4 users using a command line tool such as gcloud CLI.
Недостатки
По сравнению с рабочим процессом с использованием служебных учетных записей, у этого подхода есть несколько недостатков:
- User authentication workflow requires you to create an OAuth 2.0 client ID and secret in the Google Cloud Console, which requires more configuration steps than creating a service account and key.
- Вашему приложению, возможно, потребуется пройти дополнительную проверку в Google Cloud App .
- If the authorized user leaves the team or company, then your app may stop working if you remove the user from your accounts or disable the user account. Service accounts are not tied to individual users, so this risk is avoided.
- The user authorizing the Google Ads account should take extra precautions such as enabling 2 factor authentication to defend against their Google Account getting compromised due to getting compromised due to poor security, malware, or phishing. Service accounts are less vulnerable to this issue since some of these modes of attack don't directly apply to them.
Сгенерировать учетные данные
Follow the instructions to configure an OAuth consent screen for your application and add
https://www.googleapis.com/auth/adwordsas an OAuth 2.0 scope. See Setting up your OAuth consent screen for details.Create a client ID and client secret by following the instructions . Once you create the OAuth 2.0 client, download the client's JSON file by first clicking its Download OAuth client icon and then the DOWNLOAD JSON button on the following screen. Save the file as
credentials.json.Identify a user account that has access to all the Google Ads accounts you want to manage using your app. If there are accounts with missing access, then follow the instructions to grant the necessary access.
Загрузите и установите gcloud CLI. После установки убедитесь в корректной работе инструмента, выполнив команду `
gcloud versionиз командной строки. Результат может выглядеть следующим образом.:~$ gcloud version Google Cloud SDK 492.0.0 alpha 2024.09.06 beta 2024.09.06 bq 2.1.8 bundled-python3-unix 3.11.9 core 2024.09.06 enterprise-certificate-proxy 0.3.2 gcloud-crc32c 1.0.0 gsutil 5.30
Сгенерируйте токен обновления OAuth 2.0, запустив инструмент командной строки gcloud:
gcloud auth application-default
login --scopes=https://www.googleapis.com/auth/adwords,https://www.googleapis.com/auth/cloud-platform
--client-id-file=<path_to_credentials.json>Файл
credentials.jsonбыл получен на предыдущем шаге.The
gcloudcommand opens a Google Account login window in a new browser window and takes you through the OAuth 2.0 authentication steps. Make sure you sign in as the user you selected from the previous steps. If your app is unverified , you might see a warning screen. In such cases, it's safe to click the Show Advanced link and click the Go to PROJECT_NAME (unverified) option.
After you verify the scopes, click the Continue button to grant the permission. The browser navigates to
https://cloud.google.com/sdk/auth_success, indicating that the authentication was successful. The page displays the following message:Authorization code granted. Close this tab.Команда
gcloudвыводит следующее сообщение:Credentials saved to file: [/****/.config/gcloud/application_default_credentials.json]Теперь откройте файл
application_default_credentials.json. Его содержимое должно быть примерно следующим:{ "account": "", "client_id": "******.apps.googleusercontent.com", "client_secret": "******", "refresh_token": "******", "type": "authorized_user", "universe_domain": "googleapis.com" }
Конфигурация клиентской библиотеки
Выберите вкладку, соответствующую вашему языку программирования, чтобы получить инструкции по настройке клиентской библиотеки.
Java
Настройте следующие ключи в файле ads.properties .
api.googleads.clientId=INSERT_CLIENT_ID_HERE api.googleads.clientSecret=INSERT_CLIENT_SECRET_HERE api.googleads.refreshToken=INSERT_REFRESH_TOKEN_HERE api.googleads.loginCustomerId=INSERT_LOGIN_CUSTOMER_ID_HERE
Дополнительные параметры см. в руководстве по настройке .
.СЕТЬ
Вы можете инициализировать экземпляр GoogleAdsClient во время выполнения, используя учетные данные, полученные от пользователя, к чьим аккаунтам вы обращаетесь с API-запросами.
GoogleAdsConfig config = new GoogleAdsConfig() { OAuth2Mode = OAuth2Flow.APPLICATION, OAuth2ClientId = "INSERT_OAUTH2_CLIENT_ID", OAuth2ClientSecret = "INSERT_OAUTH2_CLIENT_SECRET", OAuth2RefreshToken = "INSERT_OAUTH2_REFRESH_TOKEN", ... }; GoogleAdsClient client = new GoogleAdsClient(config);
Дополнительные параметры см. в руководстве по настройке .
Python
Настройте следующие ключи в файле google-ads.yaml .
client_id: INSERT_OAUTH2_CLIENT_ID_HERE client_secret: INSERT_OAUTH2_CLIENT_SECRET_HERE refresh_token: INSERT_REFRESH_TOKEN_HERE login_customer_id: INSERT_LOGIN_CUSTOMER_ID_HERE
Дополнительные параметры см. в руководстве по настройке .
PHP
Настройте следующие ключи в файле google_ads_php.ini .
[GOOGLE_ADS] loginCustomerId = "INSERT_LOGIN_CUSTOMER_ID_HERE" [OAUTH2] clientId = "INSERT_OAUTH2_CLIENT_ID_HERE" clientSecret = "INSERT_OAUTH2_CLIENT_SECRET_HERE" refreshToken = "INSERT_OAUTH2_REFRESH_TOKEN_HERE"
Дополнительные параметры см. в руководстве по настройке .
Руби
Настройте следующие ключи в файле google_ads_config.rb .
Google::Ads::GoogleAds::Config.new do |c| c.client_id = 'INSERT_CLIENT_ID_HERE' c.client_secret = 'INSERT_CLIENT_SECRET_HERE' c.refresh_token = 'INSERT_REFRESH_TOKEN_HERE' c.developer_token = 'INSERT_DEVELOPER_TOKEN_HERE' c.login_customer_id = 'INSERT_LOGIN_CUSTOMER_ID_HERE' end
Дополнительные параметры см. в руководстве по настройке .
Perl
Настройте следующие ключи в файле googleads.properties .
clientId=INSERT_OAUTH2_CLIENT_ID_HERE clientSecret=INSERT_OAUTH2_CLIENT_SECRET_HERE refreshToken=INSERT_OAUTH2_REFRESH_TOKEN_HERE loginCustomerId=INSERT_LOGIN_CUSTOMER_ID_HERE
Дополнительные параметры см. в руководстве по настройке .
локон
Для начала воспользуйтесь HTTP-клиентом, чтобы получить токен доступа OAuth 2.0. В этом руководстве используется команда curl .
curl \ --data "grant_type=refresh_token" \ --data "client_id=CLIENT_ID" \ --data "client_secret=CLIENT_SECRET" \ --data "refresh_token=REFRESH_TOKEN" \ https://www.googleapis.com/oauth2/v3/token
You can now use the access token in your API calls. The following example shows how to run a campaign report using the GoogleAdsService.SearchStream method to retrieve the campaigns in your account. This guide doesn't cover the details of reporting .
curl -i -X POST https://googleads.googleapis.com/v24/customers/CUSTOMER_ID/googleAds:searchStream \ -H "Content-Type: application/json" \ -H "Authorization: Bearer ACCESS_TOKEN" \ -H "developer-token: DEVELOPER_TOKEN" \ -H "login-customer-id: LOGIN_CUSTOMER_ID" \ --data-binary "@query.json"
Содержимое файла query.json следующее:
{ "query": "SELECT campaign.id, campaign.name, campaign.network_settings.target_content_network FROM campaign ORDER BY campaign.id" }