Приложения и проекты, использующие API и SDK платформы Google Карт, должны использовать ключи API или, если поддерживается, OAuth 2.0 для аутентификации.
Эти рекомендации покажут вам, как защитить доступ к платформе Карт.
Если вы хотите использовать OAuth 2.0 для авторизации трафика между серверами , найдите раздел, посвящённый OAuth, в документации по вашему API. Подробнее см. в разделе «Использование OAuth для серверных приложений» .
Помимо ограничений, накладываемых на приложения и ключи API, соблюдайте все меры безопасности, применимые к конкретным продуктам платформы Google Карт. Например, см. раздел «Рекомендуемые ограничения на приложения и API» ниже, посвящённый Maps JavaScript API.
Если ваши ключи API уже используются, ознакомьтесь с рекомендациями ниже в разделе Если вы ограничиваете используемый ключ API .
Более подробную информацию о цифровых подписях, поддерживаемых Maps Static API и Street View Static API, см. в Руководстве по цифровым подписям .
Рекомендуемые лучшие практики
Чтобы повысить уровень безопасности и избежать выставления счетов за несанкционированное использование, следуйте этим рекомендациям по обеспечению безопасности API для всех API, SDK или сервисов платформы Google Карт:
Рекомендуется для всех вариантов использования API-ключа
Используйте отдельные ключи API для каждого приложения
Удалить неиспользуемые ключи API
Проверьте использование вашего ключа API
Будьте осторожны при ротации ключей API
Разделите использование клиентской и серверной части на отдельные проекты
Отключить неиспользуемые службы
Дополнительные рекомендации для клиентских приложений
Безопасные вызовы клиентских веб-сервисов
Дополнительные рекомендации для веб-сайтов или клиентских приложений, использующих статические веб-API
Защитите использование статического веб-API
Дополнительные рекомендации для серверных приложений, использующих веб-сервисы
Защитите ключи API веб-сервиса
Используйте OAuth для серверных приложений
Если вы ограничиваете или ротируете используемый ключ API
Прежде чем менять ключ API, проверьте использование ключа API. Этот шаг особенно важен, если вы добавляете ограничения для ключа, который уже используется в производственном приложении.
После смены ключа при необходимости обновите все свои приложения, используя новые ключи API.
Если ваш ключ API не был скомпрометирован и не используется активно, вы можете перенести свои приложения на несколько новых ключей API в удобном для вас темпе, оставив исходный ключ API нетронутым до тех пор, пока не будете наблюдать только один тип трафика, а ключ API можно будет безопасно ограничить одним типом ограничений приложений, не вызывая непреднамеренных сбоев в обслуживании.
Дополнительные инструкции см. в разделе Переход на несколько ключей API .
Отслеживайте использование с течением времени и смотрите, когда конкретные API, типы платформ и домены были перенесены со старого ключа API, прежде чем ограничить его использование или удалить. Подробнее см. в разделах «Отчётность и мониторинг» и «Метрики».
Если ваш ключ API был скомпрометирован, вам следует быстрее принять меры по его защите и пресечению злоупотреблений. В приложениях для Android и iOS ключи не заменяются, пока пользователи не обновят свои приложения. Обновление или замена ключей на веб-страницах или в серверных приложениях гораздо проще, но всё равно может потребовать тщательного планирования и быстрой работы.
Для получения дополнительной информации см. раздел Обработка несанкционированного использования ключа API .
Дополнительная информация
Рекомендуемые ограничения приложений и API
Ограничьте свои ключи API
Рекомендуется всегда ограничивать ключи API одним типом ограничений для приложений и одним или несколькими ограничениями для API. Рекомендуемые ограничения для API, SDK или службы JavaScript см. в разделе «Рекомендуемые ограничения для приложений и API» ниже.
Ограничения приложений Вы можете ограничить использование ключа API определенными платформами: приложениями Android или iOS, определенными веб-сайтами для клиентских приложений или определенными IP-адресами или подсетями CIDR для серверных приложений, выполняющих вызовы REST API веб-служб.
Вы ограничиваете ключ, добавляя одно или несколько ограничений приложений тех типов, которые вы хотите авторизовать, после чего разрешены будут только запросы, исходящие из этих источников.
Ограничения API. Вы можете ограничить API, SDK или сервисы платформы Google Карт, в которых можно использовать ваш ключ API. Ограничения API разрешают запросы только к указанным вами API и SDK. Для любого ключа API вы можете указать любое необходимое количество ограничений API. Список доступных API включает все API, включённые в проекте.
Установить ограничение приложения для ключа API
Откройте страницу учетных данных платформы Google Карт в консоли Google Cloud.
Выберите ключ API, который вы хотите ограничить.
На странице «Изменить ключ API» в разделе «Ограничения ключа » выберите «Установить ограничение приложения» .

Выберите один из типов ограничений и предоставьте запрашиваемую информацию, следуя списку ограничений.
Тип ограничения Описание Веб-сайты Укажите один или несколько сайтов-источников перехода. -  Универсально поддерживаемые схемы URL-адресов реферера — 
httpsиhttp. Корректная работа других схем не гарантируется, поскольку современные веб-браузеры из соображений конфиденциальности не отправляют заголовок `Referer` в исходящих запросах. -  Всегда указывайте полную строку реферера, включая схему протокола, имя хоста и необязательный порт (например, 
https://google.com). -  Для авторизации всех поддоменов можно использовать подстановочные знаки. Например, 
https://*.google.comпринимает все сайты, заканчивающиеся на.google.com. -  Будьте осторожны при разрешении полных путей рефереров, например, 
https://google.com/some/path, поскольку большинство веб-браузеров в целях конфиденциальности удаляют путь из запросов к другим источникам. 
IP-адреса Укажите один или несколько адресов IPv4 или IPv6, или подсетей, используя нотацию CIDR. IP-адреса должны соответствовать адресу источника, который отслеживают серверы платформы Google Карт. Если вы используете преобразование сетевых адресов (NAT) , этот адрес обычно соответствует публичному IP-адресу вашего компьютера. Android-приложения Добавьте имя пакета Android (из файла
AndroidManifest.xml) и отпечаток сертификата подписи SHA-1 каждого приложения Android, которое вы хотите авторизовать.- Выберите приложения Android .
 - Нажмите + Добавить .
 -  Введите название пакета и отпечаток сертификата SHA-1. Например: 
com.example.android.mapexample
BB:0D:AC:74:D3:21:E1:43:67:71:9B:62:91:AF:A1:66:6E:44:5D:75
 - Нажмите «Сохранить ».
 
Существует два типа сертификатов:
- Отладочный сертификат : используйте этот тип сертификата только с тестируемыми приложениями и другим непроизводственным кодом. Не пытайтесь опубликовать приложение, подписанное отладочным сертификатом. Инструменты Android SDK автоматически генерируют этот сертификат при запуске отладочной сборки.
 - Сертификат выпуска : используйте этот сертификат, когда будете готовы выпустить приложение в магазине приложений. Инструменты Android SDK генерируют этот сертификат при запуске сборки выпуска.
 
Дополнительную информацию о подписи и сертификатах приложений Android см. в руководстве «Подпишите свое приложение» .
Если вы используете Play App Signing , чтобы получить отпечаток сертификата подписи, см. раздел Работа с поставщиками API . Если вы управляете собственным ключом подписи, см. раздел Самостоятельное подписание приложения или инструкции для вашей среды сборки.
приложения для iOS Добавьте идентификатор пакета каждого приложения iOS, которое вы хотите авторизовать.
- Выберите приложения iOS .
 - Нажмите + Добавить .
 - Добавьте идентификатор пакета, чтобы принимать запросы от приложения iOS с этим идентификатором.
 - Нажмите «Сохранить ».
 
Рекомендации по ограничению применения см. в разделе Рекомендуемое ограничение применения .
-  Универсально поддерживаемые схемы URL-адресов реферера — 
 Выберите Сохранить .
Установить ограничения API для ключа API
Откройте страницу учетных данных платформы Google Карт в консоли Google Cloud.
Выберите ключ API, который вы хотите ограничить.
На странице «Изменить ключ API» в разделе «Ограничения API» :
Выберите Ограничить ключ .
Откройте Select APIs и выберите API или SDK, к которым ваше приложение должно получить доступ с помощью ключа API.
Если API или SDK отсутствуют в списке, их необходимо включить. Подробнее см. в разделе Включение одного или нескольких API или SDK .

Выберите Сохранить .
После этого шага ограничение становится частью определения ключа API. Убедитесь, что вы указали все необходимые данные, и нажмите кнопку «Сохранить», чтобы сохранить ограничения ключа API. Подробнее см. в руководстве « Получить ключ API» в документации по интересующему вас API или SDK.
Рекомендованные ограничения API см. в разделе Рекомендуемые ограничения API .
Проверьте использование вашего ключа API
Если вы ограничиваете использование ключей API после их создания или хотите узнать, какие API используются ключом, чтобы можно было их ограничить, проверьте использование ключа API. Эти шаги покажут, в каких сервисах и методах API используется ключ API. Если вы видите какое-либо использование за пределами сервисов платформы Google Карт, проведите исследование, чтобы определить, нужно ли добавить дополнительные ограничения для предотвращения нежелательного использования. Вы можете использовать обозревателя метрик Google Maps Platform Cloud Console, чтобы определить, какие ограничения API и приложений следует применить к вашему ключу API:
Определите API, которые используют ваш ключ API.
Следующие отчёты по метрикам позволяют определить, какие API используют ваши ключи API. Используйте эти отчёты для следующих целей:
- Посмотрите, как используются ваши ключи API
 - Обнаружение неожиданного использования
 - Помогите проверить, можно ли безопасно удалить неиспользуемый ключ. Подробнее об удалении ключа API см. в разделе Удаление неиспользуемых ключей API .
 
При применении ограничений API используйте эти отчёты для создания списка API для авторизации или для проверки автоматически сгенерированных рекомендаций по ограничениям ключей API. Подробнее о рекомендуемых ограничениях см. в разделе Применение рекомендуемых ограничений . Подробнее об использовании обозревателя метрик см. в разделе Создание диаграмм с помощью обозревателя метрик .
Перейдите в обозревателе метрик консоли Google Cloud.
Войдите в систему и выберите проект для ключей API, которые вы хотите проверить.
Перейдите на страницу обозревателя метрик для вашего типа API:
Для ключей API, использующих любой API , кроме Maps Embed API : перейдите на страницу обозревателя метрик .
Для ключей API, использующих Maps Embed API : перейдите в Metrics Explorer .
Проверьте каждый ключ API:
Выберите ДОБАВИТЬ ФИЛЬТР .
Выберите метку
credential_id.Выберите значение, соответствующее ключу, который вы хотите проверить.
Обратите внимание, для каких API используется этот ключ API, и подтвердите, что такое использование является ожидаемым.
После этого выберите фильтр в конце строки активного фильтра, чтобы удалить лишний фильтр.
Повторите эти действия для всех оставшихся ключей.
Ограничьте свои API-ключи только теми API, которые используются.
Если вы обнаружили несанкционированное использование, см. раздел Обработка несанкционированного использования ключа API .
Выберите правильный тип ограничения приложения с помощью обозревателя метрик.
После проверки и принятия всех необходимых мер для того, чтобы убедиться, что ваш ключ API используется только для используемых им служб платформы Google Карт, также проверьте, имеет ли ключ API правильные ограничения по применению.
Если для вашего API-ключа предусмотрены рекомендуемые ограничения, примените их. Подробнее см. в разделе Применение рекомендуемых ограничений API-ключа .
 Если ваш ключ API не имеет рекомендаций по ограничениям, определите тип ограничения приложения, который следует применить, на основе указанного platform_type с помощью обозревателя метрик:
Перейдите в обозревателе метрик консоли Google Cloud.
Войдите в систему и выберите проект для API, которые вы хотите проверить.
Перейдите на эту страницу обозревателя метрик: Обозреватель метрик .
Проверьте каждый ключ API:
Выберите ДОБАВИТЬ ФИЛЬТР .
Выберите метку
credential_id.Выберите значение, соответствующее ключу, который вы хотите проверить.
После этого выберите фильтр в конце строки активного фильтра, чтобы удалить лишний фильтр.
Повторите эти действия для всех оставшихся ключей.
Указав тип платформы для ключей API, примените ограничение приложения для этого
platform_type:PLATFORM_TYPE_JS: Применить ограничения веб-сайта к ключу.PLATFORM_TYPE_ANDROID: Применить ограничения приложений Android к ключу.PLATFORM_TYPE_IOS: Применить ограничения приложений iOS к ключу.PLATFORM_TYPE_WEBSERVICE: Для правильной настройки ограничений вам , возможно, придется полагаться на ограничения IP-адреса в ключе.Рекомендации по использованию Maps Static API и Street View Static API см. в разделе Использование Protect Static Web API .
Рекомендации по API Maps Embed см. в разделе Веб-сайты с API Maps Embed .
Мой API-ключ использует несколько типов платформ: ваш трафик невозможно надежно защитить с помощью одного API-ключа. Вам необходимо перейти на несколько API-ключей. Подробнее см. в разделе «Миграция на несколько API-ключей» .
Используйте отдельные ключи API для каждого приложения
Такая практика ограничивает область действия каждого ключа. Если один из ключей API скомпрометирован, вы можете удалить или ротировать затронутый ключ без необходимости обновления остальных ключей API. Вы можете создать до 300 ключей API для одного проекта. Подробнее см. в разделе «Ограничения на ключи API» .
Хотя один ключ API на приложение идеально подходит в целях безопасности, вы можете использовать ограниченные ключи для нескольких приложений, если они используют один и тот же тип ограничений приложений.
Применить рекомендуемые ограничения ключа API
Для некоторых владельцев проектов, редакторов и администраторов ключей API консоль Google Cloud предлагает определенные ограничения ключей API для неограниченных ключей API на основе их использования и активности на платформе Google Карт.
Если доступны, рекомендации отображаются в виде предварительно заполненных вариантов на странице учетных данных платформы Google Карт .
API и SDK платформы Google Карт, поддерживаемые автоматизированными рекомендациями
API JavaScript Карт, включая службу направлений (устаревшую), службу матриц расстояний (устаревшую), службу высот, службу геокодирования, класс Place, виджет автозаполнения Place (новый), API данных автозаполнения Place, библиотеку Places, службу Places, виджет автозаполнения Places и набор пользовательского интерфейса Places
Статический API Карт и статический API Просмотра улиц
API для встраивания карт
Maps SDK для Android, Navigation SDK для Android, Places SDK для Android и Places UI Kit для Android
Maps SDK для iOS, Navigation SDK для iOS, Places SDK для iOS, Places Swift SDK для iOS и Places UI Kit для iOS.
Причины, по которым вы можете не увидеть рекомендацию или увидеть ее неполной
Причины отсутствия рекомендаций
Вы (также) используете ключ API на сервисах, отличных от Google Maps Platform, или на сервисах Maps Platform, которые еще не поддерживаются автоматическими рекомендациями.
Если вы видите использование других сервисов, не применяйте рекомендацию, не выполнив сначала следующие действия:
Убедитесь, что использование API, которое вы видите в обозревателе метрик консоли Google Cloud, является законным.
Вручную добавьте недостающие сервисы в список API, подлежащих авторизации.
Вручную добавьте все отсутствующие ограничения приложений для служб, добавленных в список API. Если для других добавленных вами служб требуются другие ограничения приложений, см. раздел Переход на несколько ключей API .
Ваш ключ API не используется в клиентских SDK или API.
Вы используете ключ API в приложении или на веб-сайте с низкой посещаемостью, которые не использовались в течение последних 60 дней.
Вы недавно создали новый ключ или недавно развернули существующий ключ в новом приложении. В этом случае подождите ещё несколько дней, чтобы рекомендации обновились.
Вы используете ключ API в нескольких приложениях, которые требуют конфликтующих типов ограничений, или используете один и тот же ключ API в слишком большом количестве различных приложений или веб-сайтов. В любом случае рекомендуется перейти на несколько ключей. Подробнее см. в статье «Переход на несколько ключей API» .
Причины, по которым вы видите неполную рекомендацию
Вы используете ключ API в приложении или на веб-сайте с низкой посещаемостью, которые не использовались в течение последних 60 дней.
Вы совсем недавно начали использовать существующий ключ для нового API или сервиса, и система автоматического выдачи рекомендаций по ограничению использования ключей API ещё не обработала обновлённые метрики использования. Распространение метрик использования может занять несколько дней.
Если вы видите использование других сервисов, не применяйте рекомендацию, не выполнив сначала следующие действия:
Убедитесь, что использование API, которое вы видите в обозревателе метрик консоли Google Cloud, является законным.
Вручную добавьте недостающие сервисы в список API, подлежащих авторизации.
Вручную добавьте все отсутствующие ограничения приложений для служб, добавленных в список API. Если для других добавленных вами служб требуются другие ограничения приложений, см. раздел Переход на несколько ключей API .
Если вам не нужно срочно ограничить доступ к ключу, например, из-за несанкционированного использования, вы можете подождать день или два, пока рекомендации не появятся.
Причины, по которым вы можете увидеть рекомендации, которые не видны на диаграммах
Ваше приложение или веб-сайт отправляли только очень короткие всплески трафика. В этом случае переключитесь с представления «Диаграмма» на представление «Таблица» или «Оба» , так как использование по-прежнему отображается в легенде. Подробнее см. в разделе «Отображение полных легенд диаграммы» .
Ваш трафик поступает из Maps Embed API. Инструкции см. в статье «Определение API, использующих ваш ключ API» .
Трафик из приложения или веб-сайта находится за пределами диапазона дат, доступного в обозревателе метрик консоли Google Cloud.
Применять рекомендуемые ограничения
Откройте страницу учетных данных платформы Google Карт в консоли Google Cloud.
Если доступно, выберите Применить рекомендуемые ограничения .

Выберите «Проверить использование API» , чтобы проверить, для каких служб используется ключ API. Если вы видите что-то, кроме служб платформы Google Карт, приостановите просмотр и вручную проверьте приведенные выше рекомендации. См. шаги по устранению неполадок в начале раздела « Применение ограничений рекомендуемых ключей API» .
Еще раз проверьте, соответствуют ли предварительно заполненные ограничения веб-сайтам и приложениям, где вы планируете использовать свой ключ API.
Рекомендация : задокументируйте и удалите все ограничения приложений или API, не связанные с вашими сервисами. Если что-то сломается из-за непредвиденной зависимости, вы сможете снова добавить необходимые приложения или API.
Если вы заметили, что в ваших рекомендациях явно отсутствует приложение, веб-сайт или API, добавьте его вручную или подождите пару дней, чтобы рекомендация обновилась.
Если вам нужна дополнительная помощь с предложенной рекомендацией, обратитесь в службу поддержки .
Выберите Применить .
Что делать, если ваша заявка отклонена после подачи рекомендации
Если вы заметили, что приложение или веб-сайт отклоняется после применения ограничения, найдите ограничение приложения, которое необходимо добавить, в сообщении об ошибке ответа API.
Клиентские SDK и API
- Приложения на основе браузера и веб-просмотра
 Современные браузеры обычно редактируют заголовок
Refererв кросс-доменных запросах из соображений конфиденциальности, часто оставляя его только вOrigin. Однако точное поведение зависит от применяемойreferrer-policyна хостинге и может различаться в зависимости от браузера пользователя и его версии.Веб-приложения, использующие непрозрачные или локальные схемы URI для загрузки контента, как правило, требуют от браузера рендеринга или веб-представления полностью редактировать заголовок
Refererиз любых исходящих вызовов, что может привести к сбою запросов при использовании ключей API с ограничениями веб-сайта.Дополнительные инструкции см. в разделе Размещение браузерных приложений на сервере .
Инструкции по устранению неполадок для браузерных и веб-приложений:
Подробную информацию об авторизации приложения для Maps JavaScript API см. в консоли отладки браузера.
Экзотические схемы URI поддерживаются частично . Если некоторые части вашего приложения не работают с экзотической схемой URI даже после авторизации необходимого реферера, вам, вероятно, потребуется разместить приложение удалённо на сервере и загружать его по протоколу HTTPS (или HTTP).
Если вам нужна помощь с экзотическими схемами URI, обратитесь в службу поддержки .
Другие API платформы Карт обычно возвращают реферер, который необходимо авторизовать, в ответе об ошибке API, предполагая, что клиент отправил эту информацию с отклоненным запросом.
Экзотические схемы URI не поддерживаются.
- Android-приложения
 Используйте Android Debug Bridge (adb) или Logcat
- приложения для iOS
 
Приложения, напрямую вызывающие веб-сервисы
Информацию о приложениях, вызывающих конечные точки HTTPS REST API или gRPC платформы Карт напрямую без клиентского SDK платформы Google Карт, см. ниже:
- Приложения для Android и iOS
 Если ваше приложение для Android или iOS напрямую обращается к службам платформы Карт, не используя ни один из доступных клиентских SDK платформы Google Карт, ознакомьтесь с разделами Приложения для Android и iOS , где вы найдете дополнительные советы по устранению неполадок, и с разделом Безопасные вызовы клиентских веб-служб, где вы найдете актуальные рекомендации по обеспечению безопасности для случаев использования на мобильных устройствах.
Если ваше приложение регистрирует ответы на ошибки API платформы Карт, приведенные выше инструкции для клиентских SDK также могут оказаться полезными для устранения неполадок аутентификации.
- Серверные приложения
 Серверные приложения, использующие ключи API, лучше всего защищаются с помощью ограничений по IP-адресам. Если вы применили ограничения по IP-адресам к своему ключу и ваш сервис регистрирует ошибки API платформы Карт, проверьте системные журналы для получения дополнительной информации. В ответе об ошибке будет указан IP-адрес сервера, который необходимо авторизовать.
- Приложения на основе браузера или веб-просмотра
 Хотя Maps Static API, Street View Static API и более поздние API платформы Google Карт также будут поддерживать ограничения реферера, следует отметить, что веб-браузеры или веб-представления, скорее всего, будут ограничивать заголовок
RefererOriginдля запросов между источниками и, скорее всего, вообще не будут отправлять его, например, для локально доступных ресурсов или для ресурсов, обслуживаемых по протоколам, отличным от HTTP или HTTPS.Если вы не можете использовать Maps JavaScript API в своем приложении и ограничения веб-сайта не работают, ознакомьтесь со статьей Безопасные вызовы клиентских веб-служб , чтобы узнать, как безопасно выполнять вызовы веб-служб платформы Карт из клиентского приложения на основе браузера.
Советы по проверке ограничений API
Чтобы проверить требуемые ограничения API, см. раздел Определение API, которые используют ваш ключ API .
Если вы не можете определить, какие ограничения следует применить:
- Задокументируйте текущие ограничения для дальнейшего использования.
 - Временно удалите их, пока вы исследуете проблему. Вы можете проверить использование API с течением времени, следуя инструкциям в разделе Проверка использования ключа API .
 - При необходимости обратитесь в службу поддержки .
 
Удалить неиспользуемые ключи API
Прежде чем удалять ключ API, убедитесь, что он не используется в рабочей среде. Если трафик отсутствует, ключ, скорее всего, можно безопасно удалить. Подробнее см. в разделе «Проверка использования ключа API» .
Чтобы удалить ключ API:
Откройте страницу учетных данных платформы Google Карт в консоли Google Cloud.
Выберите ключ API, который вы хотите удалить.
Нажмите кнопку «Удалить» в верхней части страницы.
На странице «Удаление учетных данных» выберите Удалить .
Распространение удаления API-ключа занимает несколько минут. После завершения распространения любой трафик, использующий удалённый API-ключ, отклоняется.
Будьте осторожны при ротации ключей API
Ротация API-ключа создаёт новый ключ, обладающий всеми ограничениями старого. В течение этого периода принимаются как старый, так и новый ключ, что даёт вам возможность перевести свои приложения на использование нового ключа.
Перед ротацией ключа API :
Сначала попробуйте ограничить ваши ключи API, как описано в разделе Ограничение ваших ключей API .
Если ограничение ключа API невозможно из-за конфликта типов ограничений приложения, выполните миграцию на несколько новых (ограниченных) ключей, как описано в разделе «Миграция на несколько ключей API» . Миграция позволяет контролировать процесс миграции и планировать сроки внедрения новых ключей API.
Если предыдущие предложения невозможны и вам необходимо сменить ключ API, чтобы предотвратить несанкционированное использование, выполните следующие действия:
Откройте страницу учетных данных платформы Google Карт в консоли Google Cloud.
Откройте API-ключ, который вы хотите ротировать.
В верхней части страницы выберите Повернуть ключ .
При желании измените имя ключа API.
Выберите Создать .
Обновите свои приложения, чтобы использовать новый ключ.
После того как вы обновите свои приложения для использования нового ключа, удалите старый ключ, нажав кнопку Удалить предыдущий ключ в разделе Предыдущий ключ на странице нового ключа API.
Переход на несколько ключей API
Чтобы перейти от использования одного ключа API для нескольких приложений к одному уникальному ключу API для каждого приложения, выполните следующие действия.
Определите, каким приложениям нужны новые ключи :
- Веб-приложения обновлять проще всего, поскольку вы контролируете весь код. Запланируйте обновление ключей всех ваших веб-приложений.
 - С мобильными приложениями все гораздо сложнее, поскольку вашим клиентам придется обновить свои приложения, прежде чем можно будет использовать новые ключи.
 
Создайте и ограничьте новые ключи : добавьте ограничение для приложения и как минимум одно ограничение API. Подробнее см. в разделе «Рекомендуемые практики» .
Добавьте новые ключи в свои приложения : для мобильных приложений этот процесс может занять несколько месяцев, пока все ваши пользователи не обновятся до последней версии приложения с новым ключом API.
Разделите использование клиентской и серверной части на отдельные проекты
Если вам необходимо вызывать службы платформы Google Карт как из серверных приложений, так и напрямую из клиентских приложений, работающих на устройствах конечных пользователей, Google рекомендует разделить использование между двумя отдельными проектами.
Такой подход позволяет вам применять соответствующие поминутные ограничения квот для каждого пользователя к большинству сервисов платформы Google Карт в вашем клиентском проекте, помогая гарантировать, что все конечные пользователи получат свою справедливую долю общей квоты проекта, не влияя друг на друга.
Однако, поскольку ограничения квоты на пользователя влияют как на клиентские, так и на серверные приложения, если вам также требуется высокая пропускная способность для задач на стороне сервера, создайте отдельный проект для этого варианта использования, настроив его на более высокий предел квоты на пользователя или вообще не настроив его.
Отключить неиспользуемые службы
Не оставляйте неиспользуемые сервисы включёнными в проекте, так как это может привести к злоупотреблениям, особенно если вы не ограничили доступ ко всем своим открытым API-ключам. Рекомендуется включать сервис в проекте только тогда, когда он необходим вашим приложениям.
Добавление ограничений API к ключу предотвращает его использование в сервисах, для которых он не был авторизован, но ограничения API применяются только к этому конкретному ключу. Отключите сервис на уровне проекта, чтобы предотвратить несанкционированное использование сервиса для любого ключа, связанного с проектом.
Используйте клиентские SDK
При использовании клиентских SDK Google Maps Platform вы всегда сможете применить соответствующие ограничения к своему ключу API, чтобы обезопасить использование сервиса.
Использование клиентских SDK также позволит вам внедрить более продвинутые механизмы безопасности, такие как Firebase App Check на поддерживающих его API-интерфейсах Maps Platform. Подробнее см. в статье «Использование App Check для защиты ключа API» .
Если клиентские SDK недоступны для вашей платформы, см. раздел Защита вызовов клиентских веб-сервисов .
Информацию о доступности клиентских SDK Google Maps Platform для различных платформ см. в разделе Рекомендуемые ограничения приложений и API .
Защитите использование статического веб-API
Статические веб-API, такие как Maps Static API и Street View Static API, аналогичны вызовам API веб-сервисов.
Оба вызова выполняются через HTTPS REST API, и URL-адрес запроса API обычно генерируется на сервере. Однако вместо возврата JSON-ответа статические веб-API генерируют изображение, которое можно встроить в сгенерированный HTML-код. Что ещё важнее, обычно именно клиентская часть , а не сервер, обращается к сервису платформы Google Карт.
Используйте цифровую подпись
Рекомендуется всегда использовать цифровые подписи в дополнение к ключу API. Также определите, сколько неподписанных запросов вы готовы разрешить в день, и соответствующим образом скорректируйте квоты на неподписанные запросы .
Более подробную информацию о цифровых подписях см. в Руководстве по цифровым подписям .
Защитите свой секрет подписи
Для защиты статических веб-API не встраивайте секреты подписи API непосредственно в код или в исходный код, а также не раскрывайте их в клиентских приложениях. Следуйте этим рекомендациям по защите секретов подписи:
Сгенерируйте подписанные URL-адреса запросов Maps Static API и Street View Static API на стороне сервера при обслуживании веб-страницы или в ответ на запрос из вашего мобильного приложения .
Для статического веб-контента можно использовать виджет «Подписать URL сейчас» на странице учетных данных платформы Google Карт Cloud Console.
Для динамического веб-контента см. доступные примеры кодов подписи URL-запросов.
Храните секреты подписи вне исходного кода и дерева исходного кода вашего приложения . Если вы помещаете секреты подписи или любую другую конфиденциальную информацию в переменные окружения или включаете файлы, хранящиеся отдельно, а затем делитесь своим кодом, то секреты подписи не включаются в общие файлы. Если вы храните секреты подписи или любую другую конфиденциальную информацию в файлах, размещайте их вне дерева исходного кода вашего приложения, чтобы ваши секреты подписи не попали в систему управления исходным кодом. Эта мера предосторожности особенно важна, если вы используете общедоступную систему управления исходным кодом, например GitHub.
Защитите ключи API веб-сервиса
For secure use of Google Maps Platform APIs and services from client-side apps, see Use client-side SDKs and Secure client-side web service calls .
Store API keys outside of your application's source code or source tree . If you put your API keys or any other information in environment variables or include files that are stored separately and then share your code, the API keys are not included in the shared files. This is particularly important if you use a public source code management system, such as GitHub.
To help shield your web service API key against accidental use, Google recommends applying API restrictions to any key used for Maps Platform. Furthermore, also applying IP address restrictions to your web service key will protect it against help protect it against unauthorized use from other source IP addresses, even if the key accidentally leaks.
Use OAuth for server-side apps
OAuth 2.0 is an open standard for access delegation.
While the OAuth 2.0 protocol supports use cases, where an end user authorizes an application to access personal data on their behalf, the intended use case for OAuth 2.0 with Maps Platform is for the developer to utilize temporary access tokens for authorizing their application to call an API on behalf of their Google Cloud project service account with the permissions of the service account.
As a service account may have extremely broad permissions, OAuth 2.0 is recommended for authorizing server-to-server calls between a developer's trusted server-side applications and Google's Maps Platform servers.
For client-side applications running on end user devices, other authentication methods, such as API keys, are recommended.
If you want to use OAuth 2.0 to authorize server-to-server traffic, look for the OAuth topic in your API documentation.
For example, here is the OAuth topic for the Address Validation API .
Secure client-side web service calls
If client-side SDKs are not available, see the recommendations below.
Используйте прокси-сервер
Using a secure proxy server provides a solid source for interacting with a Google Maps Platform web service endpoint from a client-side application without exposing your API key, signing secret or Google Cloud service account to unauthorized users.
Ключевые моменты:
Construct your Google Maps Platform requests on the proxy server. Don't allow clients to relay arbitrary API calls using the proxy.
Post-process the Google Maps Platform responses on your proxy server. Filter out data that the client doesn't need.
For more information about using a proxy server, see Living Vicariously: Using Proxy Servers with the Google Data API Client Libraries .
Secure direct mobile web service calls
If you are unable to set up a secure proxy server for your client-side app, secure your application using the following steps:
Use HTTP headers:
Android : Use the
X-Android-PackageandX-Android-CertHTTP headers.iOS : Use the
X-Ios-Bundle-IdentifierHTTP header.
Add the corresponding application restrictions to your Android or iOS key.
Before you consider issuing calls directly from your mobile application to a Google Maps Platform REST API web service, verify that requests with incorrect Android or iOS application identifiers are rejected.
If Android and iOS application restrictions are not supported on the tested endpoint, Google strongly recommends that you use a secure proxy server between your mobile clients and the Google Maps Platform web service endpoint.
Tips for Android applications:
Before you integrate your Android application with Google Maps Platform services, verify that your application ID (also called package name) is formatted correctly. For details, see Configure app module . in the Android documentation.
To pass
X-Android-Packagedirectly from your application, look it up programmatically usingContext.getPackageName().To pass
X-Android-Certdirectly from your applications, calculate the required SHA-1 fingerprint of your application signing certificates, accessible throughPackageInfo.signingInfo.If you authorize your Android application using the Google Cloud console, note that the UI expects the SHA-1 fingerprint to be a colon-delimited string, eg,
00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33. However, thegcloudtool and the API keys API expect the hexadecimal string without delimiters.
Tips for iOS applications:
Before you integrate your iOS application with Google Maps Platform services, verify that your Bundle ID is formatted correctly .
You should typically always pass the Bundle ID of your main bundle in the
X-Ios-Bundle-Identifierheader, when authorizing your iOS application.
For further information, refer to articles Manage API keys and Use API keys to access APIs .
Host your browser based apps on a server
Frameworks, such as Apache Cordova, allow you to conveniently create multi-platform hybrid apps running inside a webview. However, API key website restrictions are not guaranteed to work correctly, unless your web app is loaded using HTTP or HTTPS from a website that you control and have authorized.
 Bundled resources, loaded locally from within a hybrid application, or accessed using a local file URL will in many cases prevent referrer based authorization from working as the browser engine powering your webview will omit sending the Referer header. To avoid this, host your web applications server-side, not client-side.
Alternatively, for mobile applications, consider using available native Google Maps Platform Android and iOS SDKs, instead of using a web based SDK.
Используйте App Check для защиты вашего ключа API
Certain Maps SDKs and APIs allow you to integrate with Firebase App Check . App Check provides protection for calls from your app to Google Maps Platform by blocking traffic that comes from sources other than legitimate apps. It does this by checking for a token from an attestation provider. Integrating your apps with App Check helps to protect against malicious requests, so you're not charged for unauthorized API calls.
App Check integration instructions:
Handle unauthorized use of an API key
If you detect use of your API key that is unauthorized, do the following to address the problem:
Restrict your keys : If you've used the same key in multiple apps, migrate to multiple API keys, and use separate API keys for each app. For more details, see:
If you use the Places SDK or the Maps Javascript API, you can also use App Check to secure your API Key .
Only replace or rotate keys if the following is true:
You detect unauthorized usage on keys that either cannot be restricted or are already restricted, and App Check is not applicable.
You want to move more quickly to secure your API key and stop the abuse, even if it might impact legitimate traffic from your application.
Before proceeding, read through Be careful when rotating API keys .
If you are still having issues or need help, contact support .
Recommended application and API restrictions
The following sections suggest appropriate application and API restrictions for each Google Maps Platform API, SDK or service.
Recommended API Restrictions
The following guidelines for API restrictions apply to all Google Maps Platform services:
Restrict your API key to only the APIs you are using it for, with the following exceptions:
If your app uses the Places SDK for Android or Places SDK for iOS, authorize Places API (New) or Places API, depending on the SDK versions you use. 1
If your app uses Maps JavaScript API, always authorize it on your key.
If you also use any of the following Maps JavaScript API services, you should also authorize these corresponding APIs:
Услуга Ограничение API Directions Service (Legacy) Directions API (Legacy) Distance Matrix Service (Legacy) Distance Matrix API (Legacy) Elevation Service API высоты Geocoding Service API геокодирования Place class, Place Autocomplete Widget (New) & Place Autocomplete Data API Places API (New) 2 Places Library, Places Service & Place Autocomplete Widget Places API 2 
1 For more details, see the Places SDK for Android and Places SDK for iOS documentation.
2 If you are unsure if you need to authorize Places API (New) or Places API, see the Maps JavaScript API documentation.
Вот несколько примеров:
You are using the Maps SDK for Android and Places SDK for Android, so you include the Maps SDK for Android and Places API (New) as API restrictions.
Your website uses the Maps JavaScript API Elevation Service and the Maps Static API, so you add API restrictions for all of the following APIs:
- API JavaScript Карт
 - API высоты
 - Статический API Карт
 
Recommended application Restriction
Веб-сайты
For websites using Maps JavaScript API services, Maps Static API or Street View Static API or calling recent Google Maps Platform services directly over the HTTPS REST API or gRPC, use the Websites application restriction:
1 For mobile applications, consider using the native Maps SDK for Android and Maps SDK for iOS .
2 For mobile applications, consider using the native Places SDK for Android and Places SDK for iOS .
3 See also Protect Static Web API usage .
Websites with the Maps Embed API
While using the Maps Embed API is no charge, you should still restrict any used API key to prevent abuse on other services.
Best practice : Create a separate API key for Maps Embed API use, and restrict this key to only the Maps Embed API. This restriction sufficiently secures the key, preventing its unauthorized use on any other Google service. For full control over where your Maps Embed API key can be used from, Google recommends also applying Websites application restrictions.
If you are unable to separate your Maps Embed API usage to a separate API key, secure your existing key using the Websites application restriction.
Apps and servers using web services
 For servers and client-side apps from trusted corporate internal networks using web services together with API keys, use the IP addresses application restriction.
Use for apps and servers using these APIs:
4 For mobile applications, consider using the Navigation SDK.
5 For safe mobile usage, use a secure proxy server .
6 For client-side applications, consider using the native geolocation service offered by the platform; for example, W3C Geolocation for web browsers, LocationManager or the Fused Location Provider API for Android, or the Apple Core Location framework for iOS.
7 For mobile applications, consider using the native Places SDK for Android and Places SDK for iOS .
8 For safe client-side usage, use a secure proxy server .
Android-приложения
 For apps on Android, use the Android apps application restriction. Use for apps using these SDKs:
In addition, prevent accidentally checking API keys into version control by using the Secrets Gradle Plugin to inject secrets from a local file rather than storing them in the Android Manifest.
приложения для iOS
 For apps on iOS, use the iOS apps application restriction. Use for apps and servers using these SDKs:
Дальнейшее чтение
- Управление ключами API
 - Используйте ключи API для доступа к API
 - Optimize your Google Maps Platform usage with quotas (video)
 - How to generate and restrict API keys for the Google Maps Platform (video)
 - Restricting API keys
 - Securing API keys when using Static Maps and Street View APIs
 - 15 Google Maps platform Best Practices
 
Apps and projects that use the Google Maps Platform APIs and SDKs must use API keys or, if supported, OAuth 2.0, to authenticate themselves.
These best practices show you how to secure your Maps Platform access.
If you want to use OAuth 2.0 to authorize server-to-server traffic, look for the OAuth topic in your API documentation. See Use OAuth for server-side apps for more details.
In addition to applying application and API key restrictions, follow any security practices that apply to specific Google Maps Platform products. For example, see the Maps JavaScript API below in Recommended application and API restrictions .
If your API keys are already in use, review the recommendations below in If you are restricting an API key that's in use .
For more details about digital signatures, supported by Maps Static API and Street View Static API, see the Digital Signature Guide .
Recommended best practices
For increased security and to avoid being billed for unauthorized use, follow these API security best practices for all Google Maps Platform APIs, SDKs, or services:
Recommended for all API key uses
Use separate API keys for each app
Be careful when rotating API keys
Split client-side and server-side usage into separate projects
Additional recommendations for client-side apps
Secure client-side web service calls
Additional recommendations for websites or client-side apps using Static Web APIs
Additional recommendations for server-side apps using web services
Use OAuth for server-side apps
If you are restricting or rotating an API key that's in use
Before you change the API key, Check your API key usage This step is especially important if you are adding restrictions for a key that is already in use in a production application.
After you change the key, update all of your apps with the new API keys, as needed.
If your API key has not been compromised and is not actively abused, you can migrate your apps to multiple new API keys at your own pace, leaving the original API key untouched until you only observe one type of traffic, and the API key can safely be restricted with a single type of application restrictions without causing unintended service disruptions.
For further instructions, see Migrate to multiple API keys .
Monitor the usage over time, and see when specific APIs, platform types, and domains have migrated off the old API key before you choose to restrict or delete the old key. For more information, see Reporting and monitoring and Metrics
If your API key has been compromised, you want to move more quickly to secure your API key and stop the abuse. In Android and iOS apps, keys aren't replaced until customers update their apps. Updating or replacing keys in on webpages or in server-side apps is much more straightforward, but may still require careful planning and fast work.
For more information, see Handle unauthorized use of an API key .
Дополнительная информация
Recommended application and API restrictions
Restrict your API keys
Best practice is to always restrict your API keys with one type of application restrictions and one or more API restrictions. For suggested restrictions by API, SDK, or JavaScript service, see Recommended application and API restrictions below.
Application restrictions You can limit the use of an API key to specific platforms: Android or iOS applications, or specific websites for client-side applications, or specific IP addresses or CIDR subnets for server-side apps issuing web service REST API calls.
You restrict a key by adding one or more application restrictions of the types you want to authorize, after which only requests originating from these sources are permitted.
API restrictions You can restrict which Google Maps Platform APIs, SDKs, or services on which your API key can be used. API restrictions only allow requests to the APIs and SDKs you specify. For any given API key, you can specify as many API restrictions as needed. The list of available APIs includes all APIs enabled on a project.
Set an application restriction for an API key
Open the Google Cloud console Google Maps Platform Credentials page.
Select the API key that you want to restrict.
On the Edit API key page , under Key restrictions , select Set an application restriction .

Select one of the restriction types and supply the requested information following the restriction list.
Тип ограничения Описание Веб-сайты Specify one or more referrer websites. -  The universally supported referrer URI schemes are 
httpsandhttp. Other schemes are not guaranteed to work correctly, since modern web browsers will for privacy reasons not send a `Referer` header in outgoing requests. -  Always provide the whole referrer string, including the protocol scheme, hostname and optional port (eg, 
https://google.com). -  You can use wildcard characters to authorize all subdomains. For example, 
https://*.google.comaccepts all sites ending in.google.com. -  Be careful when authorizing full-path referrers, for example, 
https://google.com/some/path, since most web browsers will for privacy reasons strip the path from cross-origin requests. 
IP-адреса Specify one or more IPv4 or IPv6 addresses, or subnets using CIDR notation. The IP addresses must match the source address the Google Maps Platform servers observe. If you use network address translation (NAT) , this address typically corresponds to your machine's public IP address. Android-приложения Add the Android package name (from the
AndroidManifest.xmlfile) and the SHA-1 signing certificate fingerprint of each Android application you want to authorize.- Select Android apps .
 - Click + Add .
 -  Enter your package name and SHA-1 certificate fingerprint. For example: 
com.example.android.mapexample
BB:0D:AC:74:D3:21:E1:43:67:71:9B:62:91:AF:A1:66:6E:44:5D:75
 - Нажмите «Сохранить ».
 
There are two certificate types:
- Debug certificate : Only use this certificate type with apps you're testing and other non-production code. Don't attempt to publish an app that's signed with a debug certificate. The Android SDK tools generate this certificate automatically when you run a debug build.
 - Release certificate : Use this certificate when you're ready to release your app to an app store. The Android SDK tools generate this certificate when you run a release build.
 
For more information about Android application signing and certificates, see the Sign your app guide .
If you use Play App Signing , to fetch the signing certificate fingerprint, see Working with API Providers . If you manage your own signing key, see Self-signing your application or refer to the instructions for your build environment.
приложения для iOS Add the bundle identifier of each iOS application you want to authorize.
- Select iOS apps .
 - Click + Add .
 - Add the bundle ID to accept requests from the iOS app with that ID.
 - Нажмите «Сохранить ».
 
For recommendations for an application restriction, see Recommended application Restriction .
-  The universally supported referrer URI schemes are 
 Выберите Сохранить .
Set API restrictions for an API key
Open the Google Cloud console Google Maps Platform Credentials page.
Select the API key that you want to restrict.
On the Edit API key page , under API restrictions :
Select Restrict key .
Open Select APIs and select the APIs or SDKs you want your application to access using the API key.
If an API or SDK is not listed, you need to enable it. For details, see To enable one or more APIs or SDKs .

Выберите Сохранить .
The restriction becomes part of the API key definition after this step. Be sure you provide the appropriate details and select Save to save your API key restrictions. For further information, see the Get an API Key guide in the documentation for the specific API or SDK you are interested in.
For recommended API restrictions, see Recommended API Restrictions .
Check your API key usage
If you're restricting API keys after they've been created, or if you want to see what APIs are being used by a key so you can restrict them, you want to check your API key usage. These steps show you in which services and API methods an API key is being used. If you see any usage beyond Google Maps Platform services, investigate to determine if you need to add more restrictions to avoid unwanted use. You can use the Google Maps Platform Cloud Console Metrics explorer to help determine which API and application restrictions to apply to your API key:
Determine the APIs that use your API key
The following metrics reports allow you to determine which APIs are using your API keys. Use these reports to do the following:
- See how your API keys are used
 - Spot unexpected usage
 - Help verify if an unused key is safe to delete. For information about deleting an API key, see Delete unused API keys .
 
When applying API restrictions, use these reports to create a list of APIs to authorize, or to validate automatically-generated API key restriction recommendations. For more information about recommended restrictions, see Apply recommended restrictions . For more information about using the Metrics explorer, see Create charts with Metrics explorer .
Go to the Google Cloud console's Metrics explorer
Sign in and select the project for the API keys you want to check.
Go to the Metrics explorer page for your type of API:
For API keys using any API except the Maps Embed API : Go to Metrics explorer page.
For API keys using Maps Embed API : Go to Metrics Explorer .
Inspect each API key:
Select ADD FILTER .
Select the label
credential_id.Select the value corresponding to the key you want to inspect.
Note which APIs this API key is being used for, and confirm the use is expected.
Once done, select Remove filter at the end of the active filter line to delete the extra filter.
Repeat for any remaining keys.
Restrict your API keys to only the APIs that are being used.
If you spot unauthorized use, see Handle unauthorized use of an API key .
Choose the correct type of application restriction using the Metrics explorer
After you have verified and taken any needed actions to make sure your API key is only used for the Google Maps Platform services it is using, also verify the API key has the correct application restrictions.
If your API key has recommended API key restrictions, apply them. For more information, see Apply recommended API key restrictions .
 If your API key doesn't have restriction recommendations, determine the type of application restriction to apply, based on the reported platform_type using the Metrics explorer:
Go to the Google Cloud console's Metrics explorer
Sign in and select the project for the APIs you want to check.
Go to this Metrics explorer page: Metrics explorer .
Inspect each API key:
Select ADD FILTER .
Select the label
credential_id.Select the value corresponding to the key you want to inspect.
Once done, select Remove filter at the end of the active filter line to delete the extra filter.
Repeat for any remaining keys.
Once you have the platform type for your API keys, apply the application restriction for that
platform_type:PLATFORM_TYPE_JS: Apply Website restrictions on the key.PLATFORM_TYPE_ANDROID: Apply Android application restrictions on the key.PLATFORM_TYPE_IOS: Apply iOS application restrictions on the key.PLATFORM_TYPE_WEBSERVICE: You may have to rely on IP address restrictions on the key, to properly restrict it.For recommendations for Maps Static API and Street View Static API, see Protect Static Web API usage .
For Maps Embed API recommendations, see Websites with the Maps Embed API .
My API key is using multiple platform types: Your traffic can't be properly secured with just a single API key. You need to migrate to multiple API keys. For more information, see Migrate to multiple API keys .
Use separate API keys for each app
This practice limits the scope of each key. If one API key is compromised, you can delete or rotate the impacted key without needing to update your other API keys. You can create up to 300 API keys per project. For more information, see Limits on API keys .
While one API key per application is ideal for security purposes, you can use restricted keys on multiple apps as long as they use the same type of application restriction.
Apply recommended API key restrictions
For some project owners, editors and API key administrators, the Google Cloud console suggests specific API key restrictions to unrestricted API keys based on their Google Maps Platform usage and activity.
If available, recommendations appear as pre-filled options on the Google Maps Platform Credentials page.
Google Maps Platform APIs and SDKs supported by the automated recommendations
Maps JavaScript API, including Directions Service (Legacy), Distance Matrix Service (Legacy), Elevation Service, Geocoding Service Place class, Place Autocomplete Widget (New), Place Autocomplete Data API, Places Library, Places Service, Place Autocomplete Widget, and Places UI Kit
Maps Static API and Street View Static API
API для встраивания карт
Maps SDK for Android, Navigation SDK for Android, Places SDK for Android, and Places UI Kit on Android
Maps SDK for iOS, Navigation SDK for iOS, Places SDK for iOS, Places Swift SDK for iOS, and Places UI Kit on iOS.
Reasons you may not see a recommendation, or an incomplete one
Reasons for seeing no recommendation
You are (also) using the API key on other than Google Maps Platform services, or or Maps Platform services that are not yet supported by the automatic recommendations.
If you see usage on other services, don't apply the recommendation without first doing the following:
Verify that the API usage you see in the Google Cloud console Metrics explorer is legitimate.
Manually add missing services to the list of APIs to be authorized.
Manually add any missing application restrictions for the services added to the API list. If your other added would require a different type of application restrictions, see Migrate to multiple API keys .
Your API key is not used in client-side SDKs or APIs.
You use the API key in a low-volume app or website that has not seen usage over the last 60 days.
You have created a new key very recently, or you have very recently deployed an existing key in a new app. If this is the case, just wait a few more days to allow the recommendations to update.
You are using the API key in multiple applications that would require conflicting types of application restrictions, or you are using the same API key in too many different apps or websites. In either case, as a best practice, you should migrate to multiple keys. For more details, see Migrate to multiple API keys .
Reasons for seeing an incomplete recommendation
You use the API key in a low-volume app or website that has not seen usage over the last 60 days.
You have very recently started using a existing key on a new API or service, and the automatic API key restriction recommendation pipeline, has not yet processed the updated usage metrics. The propagation of usage metrics may take a few days.
If you see usage on other services, don't apply the recommendation without first doing the following:
Verify that the API usage you see in the Google Cloud console Metrics explorer is legitimate.
Manually add missing services to the list of APIs to be authorized.
Manually add any missing application restrictions for the services added to the API list. If your other added would require a different type of application restrictions, see Migrate to multiple API keys .
Unless you urgently need to restrict a key, for example, due to unauthorized use, you might also wait a day or two for the recommendations to catch up.
Reasons you might see recommendations that are not visible in the charts
Your app or website sent only very short traffic bursts. In this case, switch from a CHART view to display a TABLE or BOTH , as the usage is still visible in the legend. For more information, see Toggling the chart's full legends .
Your traffic is from the Maps Embed API. For instructions, see Determine the APIs that use your API key .
The traffic from the app or website is outside the date range available in the Google Cloud console Metrics explorer.
To apply recommended restrictions
Open the Google Cloud console Google Maps Platform Credentials page.
If available, select Apply recommended restrictions .

Select Check API usage to verify which services the API key is being used on. If you see other than Google Maps Platform services, pause to manually review the recommendation steps above. See the troubleshooting steps at the beginning of section Apply recommended API key restrictions .
Double-check that the pre-filled restrictions match the websites and apps where you expect to use your API key.
Best Practice : Document and remove any application or API restrictions that are not affiliated with your services. If something breaks due to an unexpected dependency, then you can add the required apps or APIs back in.
If you recognize that an app, website or API is clearly missing from your recommendation, add it manually or wait a couple of days to allow the recommendation to update.
If you need further help with your suggested recommendation, contact support .
Выберите Применить .
What to do if your application gets rejected after applying a recommendation
If you notice that an app or website gets rejected after applying a restriction, look for the application restriction you need to add in the API response error message.
Client-side SDKs and APIs
- Browser and webview based apps
 Modern browsers typically redact the
Refererheader in cross-origin request for privacy reasons, often stripping it down to theOrigin. However, the exact behavior depends on the appliedreferrer-policyof the hosting site, and may also vary, based on the user browser and version.Web applications using opaque or local URI schemes for loading content will typically have the rendering browser or webview completely redact the
Refererheader from any outgoing calls, which may cause requests to fail using API keys with website restrictions.For further guidance, see Host your browser based apps on a server .
Troubleshooting instructions for browser and webview based apps:
For Maps JavaScript API, see the browser debug console for details on how to authorize your application.
Exotic URI schemes are partially supported. If parts of your application don't work it an exotic URI scheme, even after authorizing the required referrer, you will likely need to host your application remotely on a server and load it over HTTPS (or HTTP).
If you need help with exotic URI schemes, contact support .
Other Maps Platform APIs will generally return the referrer you need to authorize in the API error response, presuming the client sent this information with the rejected request.
Exotic URI schemes are not supported.
- Android-приложения
 Use Android Debug Bridge (adb) or Logcat
- приложения для iOS
 
Apps calling web services directly
For applications calling Maps Platform HTTPS REST API or gRPC endpoints directly without a client-side Google Maps Platform SDK, see below:
- Android and iOS apps
 If your Android or iOS application calls Maps Platform services directly without using any of the available Google Maps Platform client SDKs, see Android apps and iOS apps for further troubleshooting tips, and Secure client-side web service calls for current best security practices for mobile use cases.
If your app logs Maps Platform API error responses, the above instructions for client-side SDKs may also prove useful for troubleshooting authentication issues.
- Server-side apps
 Server-side applications relying on API keys are best secured through IP address restrictions. If you have applied IP address restrictions to your key, and your service logs Maps Platform API error responses, check your system logs for further information. The error response will include the server IP address that you need to authorize.
- Browser or webview based apps
 While Maps Static API, Street View Static API more recent Google Maps Platform APIs will also support referrer restrictions, note that web browsers or webviews will likely restrict the
Refererheader to theOriginfor cross-origin requests, and will likely omiy sending it altogether, eg, for locally accessed resources, or for resources served over protocols other than HTTP or HTTPS.If you can't use Maps JavaScript API in your application, and website restrictions don't work, see Secure client-side web service calls for how to issue Maps Platform web service calls securely from within your browser based client-side application.
Tips for checking API restrictions
To check your required API restrictions, see Determine the APIs that use your API key .
If you are unable to determine which restrictions to apply:
- Document the current restrictions for future reference.
 - Remove them temporarily while you investigate the issue. You can check your usage over time using the steps in Check your API key usage .
 - If needed, contact support .
 
Delete unused API keys
Before you delete an API key, make sure that it is not used in production. If there is no successful traffic, the key is likely safe to delete. For more information, see Check your API key usage .
To delete an API key:
Open the Google Cloud console Google Maps Platform Credentials page.
Select the API key you want to delete.
Select the Delete button near the top of the page.
On the Delete credential page, select Delete .
Deleting an API key takes a few minutes to propagate. After propagation completes, any traffic using the deleted API key is rejected.
Be careful when rotating API keys
Rotating an API key creates a new key that has all the old key's restrictions. During this time window, both the old and new key are accepted, giving you a chance to migrate your apps to use the new key.
Before rotating an API key :
First try to restrict your API keys as described in Restrict your API keys .
If restricting your API key is not possible due to conflicting application restriction types, migrate to multiple new (restricted) keys as described in Migrate to multiple API keys . Migrating lets you control the migration and roll out timeline to the new API keys.
If the preceding suggestions aren't possible , and you must rotate your API key to prevent unauthorized use, then follow these steps:
Open the Google Cloud console Google Maps Platform Credentials page.
Open the API key you want to rotate.
At the top of the page, select Rotate key .
Optionally, change the API key name.
Выберите Создать .
Update your applications to use the new key.
After you have updated your applications to using the new key, delete the old key by clicking the Delete the previous key button under the Previous Key section of the new API key page.
Migrate to multiple API keys
To migrate from using one API key for multiple apps to a single unique API key for each app, do the following:
Identify which apps need new keys :
- Web apps are the easiest to update, since you control all of the code. Plan to update all of your web-based apps' keys.
 - Mobile apps are much harder, since your customers must update their apps before the new keys can be used.
 
Create and restrict the new keys : Add both an application restriction and at least one API restriction. For more information, see Recommended best practices .
Add the new keys to your apps : For mobile apps, this process may take months until all of your users update to the latest app with the new API key.
Split client-side and server-side usage into separate projects
If you need to call Google Maps Platform services both from server-side applications and directly from client-side applications running end-user devices, Google recommends splitting up your usage between two separate projects.
This approach lets you apply appropriate per-minute, per-user quota limits on most Google Maps Platform services on your client-side project, helping to make sure all end users get their fair share of your overall project quota without impacting each other.
However, since per-user quota restrictions impact both client-side and server-side applications, if you also require high bandwidth for your server-side jobs, set up a separate project for this use case, configured with a higher per-user quota limit, or no limit at all.
Disable unused services
Don't leave unused services enabled on a project, as this practice is vulnerable to abuse, especially if you have not restricted all your public API keys. As a best practice, only enable a service on a project once it is needed by your applications.
Adding API restrictions on a key prevent its use on services that it hasn't been authorized for, but API restrictions only apply to that specific key. Disable a service at the project level to prevents unauthorized use of the service on any key linked to the project.
Use client-side SDKs
When using provided client-side Google Maps Platform SDKs, you will always be able to apply proper restrictions to your API key to secure your service usage.
Using client-side SDKs will also allow you to adopt more advanced security mechanism, such as Firebase App Check on the Maps Platform API surfaces that support it. See Use App Check to secure your API key for further details.
If client-side SDKs are not available for your platform, see Secure your client-side web service calls .
For the availability of client-side Google Maps Platform SDKs for different platforms, see Recommended application and API restrictions .
Protect Static Web API usage
Static Web APIs, such as the Maps Static API and Street View Static API, are similar to web service API calls.
You call both using an HTTPS REST API, and you typically generate the API request URL on the server. However, instead of returning a JSON response, Static Web APIs generate an image that you can embed in generated HTML code. More importantly, it is generally the end-user client , not the server, that calls the Google Maps Platform service.
Use a digital signature
As a best practice, always use digital signatures in addition to an API key. Also, review how many unsigned requests you want to allow per day and adjust your unsigned request quotas accordingly.
For more details about digital signatures, see the Digital Signature Guide .
Protect your signing secret
To protect Static Web APIs, don't embed your API signing secrets directly in code or in the source tree, or expose them in client-side applications. Follow these best practices for protecting your signing secrets:
Generate your signed Maps Static API and Street View Static API request URLs server-side when serving a web page, or in response to a request from your mobile application .
For static web content, you can use the Sign a URL now widget on the Cloud Console Google Maps Platform Credentials page.
For dynamic web content, see the available URL request signing code samples .
Store signing secrets outside of your application's source code and source tree . If you put your signing secrets or any other private information in environment variables or include files that are stored separately and then share your code, then signing secrets are not included in the shared files. If you store signing secrets or any other private information in files, keep the files outside your application's source tree to keep your signing secrets out of your source code control system. This precaution is particularly important if you use a public source code management system, such as GitHub.
Protect web service API keys
For secure use of Google Maps Platform APIs and services from client-side apps, see Use client-side SDKs and Secure client-side web service calls .
Store API keys outside of your application's source code or source tree . If you put your API keys or any other information in environment variables or include files that are stored separately and then share your code, the API keys are not included in the shared files. This is particularly important if you use a public source code management system, such as GitHub.
To help shield your web service API key against accidental use, Google recommends applying API restrictions to any key used for Maps Platform. Furthermore, also applying IP address restrictions to your web service key will protect it against help protect it against unauthorized use from other source IP addresses, even if the key accidentally leaks.
Use OAuth for server-side apps
OAuth 2.0 is an open standard for access delegation.
While the OAuth 2.0 protocol supports use cases, where an end user authorizes an application to access personal data on their behalf, the intended use case for OAuth 2.0 with Maps Platform is for the developer to utilize temporary access tokens for authorizing their application to call an API on behalf of their Google Cloud project service account with the permissions of the service account.
As a service account may have extremely broad permissions, OAuth 2.0 is recommended for authorizing server-to-server calls between a developer's trusted server-side applications and Google's Maps Platform servers.
For client-side applications running on end user devices, other authentication methods, such as API keys, are recommended.
If you want to use OAuth 2.0 to authorize server-to-server traffic, look for the OAuth topic in your API documentation.
For example, here is the OAuth topic for the Address Validation API .
Secure client-side web service calls
If client-side SDKs are not available, see the recommendations below.
Используйте прокси-сервер
Using a secure proxy server provides a solid source for interacting with a Google Maps Platform web service endpoint from a client-side application without exposing your API key, signing secret or Google Cloud service account to unauthorized users.
Ключевые моменты:
Construct your Google Maps Platform requests on the proxy server. Don't allow clients to relay arbitrary API calls using the proxy.
Post-process the Google Maps Platform responses on your proxy server. Filter out data that the client doesn't need.
For more information about using a proxy server, see Living Vicariously: Using Proxy Servers with the Google Data API Client Libraries .
Secure direct mobile web service calls
If you are unable to set up a secure proxy server for your client-side app, secure your application using the following steps:
Use HTTP headers:
Android : Use the
X-Android-PackageandX-Android-CertHTTP headers.iOS : Use the
X-Ios-Bundle-IdentifierHTTP header.
Add the corresponding application restrictions to your Android or iOS key.
Before you consider issuing calls directly from your mobile application to a Google Maps Platform REST API web service, verify that requests with incorrect Android or iOS application identifiers are rejected.
If Android and iOS application restrictions are not supported on the tested endpoint, Google strongly recommends that you use a secure proxy server between your mobile clients and the Google Maps Platform web service endpoint.
Tips for Android applications:
Before you integrate your Android application with Google Maps Platform services, verify that your application ID (also called package name) is formatted correctly. For details, see Configure app module . in the Android documentation.
To pass
X-Android-Packagedirectly from your application, look it up programmatically usingContext.getPackageName().To pass
X-Android-Certdirectly from your applications, calculate the required SHA-1 fingerprint of your application signing certificates, accessible throughPackageInfo.signingInfo.If you authorize your Android application using the Google Cloud console, note that the UI expects the SHA-1 fingerprint to be a colon-delimited string, eg,
00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33. However, thegcloudtool and the API keys API expect the hexadecimal string without delimiters.
Tips for iOS applications:
Before you integrate your iOS application with Google Maps Platform services, verify that your Bundle ID is formatted correctly .
You should typically always pass the Bundle ID of your main bundle in the
X-Ios-Bundle-Identifierheader, when authorizing your iOS application.
For further information, refer to articles Manage API keys and Use API keys to access APIs .
Host your browser based apps on a server
Frameworks, such as Apache Cordova, allow you to conveniently create multi-platform hybrid apps running inside a webview. However, API key website restrictions are not guaranteed to work correctly, unless your web app is loaded using HTTP or HTTPS from a website that you control and have authorized.
 Bundled resources, loaded locally from within a hybrid application, or accessed using a local file URL will in many cases prevent referrer based authorization from working as the browser engine powering your webview will omit sending the Referer header. To avoid this, host your web applications server-side, not client-side.
Alternatively, for mobile applications, consider using available native Google Maps Platform Android and iOS SDKs, instead of using a web based SDK.
Используйте App Check для защиты вашего ключа API
Certain Maps SDKs and APIs allow you to integrate with Firebase App Check . App Check provides protection for calls from your app to Google Maps Platform by blocking traffic that comes from sources other than legitimate apps. It does this by checking for a token from an attestation provider. Integrating your apps with App Check helps to protect against malicious requests, so you're not charged for unauthorized API calls.
App Check integration instructions:
Handle unauthorized use of an API key
If you detect use of your API key that is unauthorized, do the following to address the problem:
Restrict your keys : If you've used the same key in multiple apps, migrate to multiple API keys, and use separate API keys for each app. For more details, see:
If you use the Places SDK or the Maps Javascript API, you can also use App Check to secure your API Key .
Only replace or rotate keys if the following is true:
You detect unauthorized usage on keys that either cannot be restricted or are already restricted, and App Check is not applicable.
You want to move more quickly to secure your API key and stop the abuse, even if it might impact legitimate traffic from your application.
Before proceeding, read through Be careful when rotating API keys .
If you are still having issues or need help, contact support .
Recommended application and API restrictions
The following sections suggest appropriate application and API restrictions for each Google Maps Platform API, SDK or service.
Recommended API Restrictions
The following guidelines for API restrictions apply to all Google Maps Platform services:
Restrict your API key to only the APIs you are using it for, with the following exceptions:
If your app uses the Places SDK for Android or Places SDK for iOS, authorize Places API (New) or Places API, depending on the SDK versions you use. 1
If your app uses Maps JavaScript API, always authorize it on your key.
If you also use any of the following Maps JavaScript API services, you should also authorize these corresponding APIs:
Услуга Ограничение API Directions Service (Legacy) Directions API (Legacy) Distance Matrix Service (Legacy) Distance Matrix API (Legacy) Elevation Service API высоты Geocoding Service API геокодирования Place class, Place Autocomplete Widget (New) & Place Autocomplete Data API Places API (New) 2 Places Library, Places Service & Place Autocomplete Widget Places API 2 
1 For more details, see the Places SDK for Android and Places SDK for iOS documentation.
2 If you are unsure if you need to authorize Places API (New) or Places API, see the Maps JavaScript API documentation.
Вот несколько примеров:
You are using the Maps SDK for Android and Places SDK for Android, so you include the Maps SDK for Android and Places API (New) as API restrictions.
Your website uses the Maps JavaScript API Elevation Service and the Maps Static API, so you add API restrictions for all of the following APIs:
- API JavaScript Карт
 - API высоты
 - Статический API Карт
 
Recommended application Restriction
Веб-сайты
For websites using Maps JavaScript API services, Maps Static API or Street View Static API or calling recent Google Maps Platform services directly over the HTTPS REST API or gRPC, use the Websites application restriction:
1 For mobile applications, consider using the native Maps SDK for Android and Maps SDK for iOS .
2 For mobile applications, consider using the native Places SDK for Android and Places SDK for iOS .
3 See also Protect Static Web API usage .
Websites with the Maps Embed API
While using the Maps Embed API is no charge, you should still restrict any used API key to prevent abuse on other services.
Best practice : Create a separate API key for Maps Embed API use, and restrict this key to only the Maps Embed API. This restriction sufficiently secures the key, preventing its unauthorized use on any other Google service. For full control over where your Maps Embed API key can be used from, Google recommends also applying Websites application restrictions.
If you are unable to separate your Maps Embed API usage to a separate API key, secure your existing key using the Websites application restriction.
Apps and servers using web services
 For servers and client-side apps from trusted corporate internal networks using web services together with API keys, use the IP addresses application restriction.
Use for apps and servers using these APIs:
4 For mobile applications, consider using the Navigation SDK.
5 For safe mobile usage, use a secure proxy server .
6 For client-side applications, consider using the native geolocation service offered by the platform; for example, W3C Geolocation for web browsers, LocationManager or the Fused Location Provider API for Android, or the Apple Core Location framework for iOS.
7 For mobile applications, consider using the native Places SDK for Android and Places SDK for iOS .
8 For safe client-side usage, use a secure proxy server .
Android-приложения
 For apps on Android, use the Android apps application restriction. Use for apps using these SDKs:
In addition, prevent accidentally checking API keys into version control by using the Secrets Gradle Plugin to inject secrets from a local file rather than storing them in the Android Manifest.
приложения для iOS
 For apps on iOS, use the iOS apps application restriction. Use for apps and servers using these SDKs:
Дальнейшее чтение
- Управление ключами API
 - Используйте ключи API для доступа к API
 - Optimize your Google Maps Platform usage with quotas (video)
 - How to generate and restrict API keys for the Google Maps Platform (video)
 - Restricting API keys
 - Securing API keys when using Static Maps and Street View APIs
 - 15 Google Maps platform Best Practices