В этом документе объясняется, как приложения веб-сервера используют клиентские библиотеки API Google или конечные точки Google OAuth 2.0 для реализации авторизации OAuth 2.0 для доступа к API Google.
OAuth 2.0 позволяет пользователям предоставлять приложению доступ к определённым данным, сохраняя при этом конфиденциальность своих имён, паролей и другой информации. Например, приложение может использовать OAuth 2.0 для получения разрешения пользователя на хранение файлов на Google Дисках.
Этот процесс OAuth 2.0 предназначен специально для авторизации пользователей. Он разработан для приложений, которые могут хранить конфиденциальную информацию и отслеживать состояние. Правильно авторизованное веб-серверное приложение может получить доступ к API во время взаимодействия пользователя с приложением или после того, как пользователь покинул приложение.
Приложения веб-сервера также часто используют учётные записи служб для авторизации запросов API, особенно при вызове облачных API для доступа к данным проекта, а не к данным, относящимся к конкретному пользователю. Приложения веб-сервера могут использовать учётные записи служб совместно с авторизацией пользователя.
Клиентские библиотеки
Примеры на этой странице, специфичные для разных языков, используют клиентские библиотеки Google API для реализации авторизации OAuth 2.0. Для запуска примеров кода необходимо сначала установить клиентскую библиотеку для вашего языка.
При использовании клиентской библиотеки Google API для обработки процесса OAuth 2.0 в вашем приложении клиентская библиотека выполняет множество действий, которые приложению в противном случае пришлось бы выполнять самостоятельно. Например, она определяет, когда приложение может использовать или обновлять сохранённые токены доступа, а также когда приложению необходимо повторно получать согласие. Клиентская библиотека также генерирует корректные URL-адреса перенаправления и помогает реализовать обработчики перенаправлений, которые обмениваются кодами авторизации на токены доступа.
Клиентские библиотеки Google API для серверных приложений доступны для следующих языков:
Предпосылки
Включите API для вашего проекта
Любое приложение, которое вызывает API Google, должно включить эти API в API Console.
Чтобы включить API для вашего проекта:
- Open the API Library в Google API Console.
- If prompted, select a project, or create a new one.
- The API Library Здесь перечислены все доступные API, сгруппированные по семействам продуктов и популярности. Если API, который вы хотите включить, отсутствует в списке, воспользуйтесь поиском или нажмите «Просмотреть все» в семействе продуктов, к которому он принадлежит.
- Выберите API, который вы хотите включить, затем нажмите кнопку Включить .
- If prompted, enable billing.
- If prompted, read and accept the API's Terms of Service.
Создать учетные данные авторизации
Любое приложение, использующее OAuth 2.0 для доступа к API Google, должно иметь учётные данные авторизации, которые идентифицируют приложение на сервере OAuth 2.0 Google. Ниже описано, как создать учётные данные для вашего проекта. Затем ваши приложения смогут использовать эти учётные данные для доступа к API, которые вы включили для этого проекта.
- Go to the Clients page.
- Нажмите «Создать клиента» .
- Выберите тип приложения Веб-приложение .
- Заполните форму и нажмите «Создать» . Приложения, использующие такие языки и фреймворки, как PHP, Java, Python, Ruby и .NET, должны указывать авторизованные URI перенаправления . URI перенаправления — это конечные точки, на которые сервер OAuth 2.0 может отправлять ответы. Эти конечные точки должны соответствовать правилам валидации Google .
Для тестирования вы можете указать URI, ссылающиеся на локальный компьютер, например
http://localhost:8080
. Имейте это в виду, что во всех примерах в этом документе в качестве URI перенаправления используетсяhttp://localhost:8080
.Мы рекомендуем вам спроектировать конечные точки авторизации вашего приложения таким образом, чтобы ваше приложение не предоставляло коды авторизации другим ресурсам на странице.
После создания учетных данных загрузите файл client_secret.json с сайта API Console. Сохраните файл в безопасном месте, к которому имеет доступ только ваше приложение.
Определить области доступа
Области действия позволяют вашему приложению запрашивать доступ только к тем ресурсам, которые ему необходимы, а также позволяют пользователям контролировать объём предоставляемого им доступа. Таким образом, между количеством запрашиваемых областей действия и вероятностью получения согласия пользователя может существовать обратная зависимость.
Прежде чем приступить к внедрению авторизации OAuth 2.0, мы рекомендуем вам определить области, на доступ к которым вашему приложению потребуется разрешение.
Мы также рекомендуем, чтобы ваше приложение запрашивало доступ к областям авторизации посредством процесса инкрементальной авторизации , в рамках которого ваше приложение запрашивает доступ к пользовательским данным в контексте. Эта практика помогает пользователям лучше понять, зачем вашему приложению нужен запрашиваемый доступ.
Документ «Области действия API OAuth 2.0» содержит полный список областей действия, которые можно использовать для доступа к API Google.
Требования к конкретному языку
Для запуска любого из примеров кода из этого документа вам потребуется учётная запись Google, доступ к Интернету и веб-браузер. Если вы используете одну из клиентских библиотек API, ознакомьтесь также с требованиями к конкретному языку ниже.
PHP
Для запуска примеров PHP-кода из этого документа вам понадобится:
- PHP 8.0 или выше с установленным интерфейсом командной строки (CLI) и расширением JSON.
- Инструмент управления зависимостями Composer .
Клиентская библиотека Google API для PHP:
composer require google/apiclient:^2.15.0
Дополнительную информацию см. в Клиентской библиотеке API Google для PHP .
Питон
Для запуска примеров кода Python из этого документа вам понадобится:
- Python 3.7 или выше
- Инструмент управления пакетами pip .
- Выпуск клиентской библиотеки Google API для Python 2.0:
pip install --upgrade google-api-python-client
google-auth
,google-auth-oauthlib
иgoogle-auth-httplib2
для авторизации пользователей.pip install --upgrade google-auth google-auth-oauthlib google-auth-httplib2
- Фреймворк веб-приложений Flask Python.
pip install --upgrade flask
- Библиотека HTTP-
requests
.pip install --upgrade requests
Если вы не можете обновить Python, ознакомьтесь с заметками о выпуске клиентской библиотеки Python API Google и соответствующим руководством по миграции.
Руби
Для запуска примеров кода Ruby из этого документа вам понадобится:
- Ruby 2.6 или выше
Библиотека аутентификации Google для Ruby:
gem install googleauth
Клиентские библиотеки для API Google Диска и Календаря:
gem install google-apis-drive_v3 google-apis-calendar_v3
Фреймворк веб-приложений Sinatra Ruby.
gem install sinatra
Node.js
Для запуска примеров кода Node.js из этого документа вам понадобится:
- Поддерживаемая LTS, активная LTS или текущая версия Node.js.
Клиент Node.js API Google:
npm install googleapis crypto express express-session
HTTP/REST
Вам не нужно устанавливать какие-либо библиотеки, чтобы иметь возможность напрямую вызывать конечные точки OAuth 2.0.
Получение токенов доступа OAuth 2.0
Следующие шаги показывают, как ваше приложение взаимодействует с сервером OAuth 2.0 Google для получения согласия пользователя на выполнение API-запроса от его имени. Ваше приложение должно получить это согласие, прежде чем сможет выполнить запрос к API Google, требующий авторизации пользователя.
Список ниже кратко суммирует эти шаги:
- Ваше приложение определяет необходимые ему разрешения.
- Ваше приложение перенаправляет пользователя в Google вместе со списком запрошенных разрешений.
- Пользователь сам решает, предоставлять ли разрешения вашему приложению.
- Ваше приложение узнает, какое решение принял пользователь.
- Если пользователь предоставил запрошенные разрешения, ваше приложение извлекает токены, необходимые для выполнения API-запросов от имени пользователя.
Шаг 1: Установите параметры авторизации
Первый шаг — создание запроса на авторизацию. Этот запрос устанавливает параметры, идентифицирующие ваше приложение, и определяет разрешения, которые пользователю будет предложено предоставить вашему приложению.
- Если вы используете клиентскую библиотеку Google для аутентификации и авторизации OAuth 2.0, вы создаете и настраиваете объект, который определяет эти параметры.
- Если вы вызовете конечную точку Google OAuth 2.0 напрямую, вы сгенерируете URL-адрес и зададите параметры для этого URL-адреса.
На вкладках ниже описаны поддерживаемые параметры авторизации для приложений веб-сервера. Примеры для разных языков также показывают, как использовать клиентскую библиотеку или библиотеку авторизации для настройки объекта, задающего эти параметры.
PHP
Следующий фрагмент кода создает объект Google\Client()
, который определяет параметры в запросе авторизации.
Этот объект использует информацию из файла client_secret.json для идентификации вашего приложения. (Подробнее об этом файле см. в разделе «Создание учётных данных авторизации» .) Объект также определяет области действия, к которым ваше приложение запрашивает разрешение, и URL-адрес конечной точки авторизации вашего приложения, которая будет обрабатывать ответ сервера Google OAuth 2.0. Наконец, код задаёт необязательные параметры access_type
и include_granted_scopes
.
Например, этот код запрашивает автономный доступ только для чтения к метаданным Google Диска и событиям Календаря пользователя:
use Google\Client; $client = new Client(); // Required, call the setAuthConfig function to load authorization credentials from // client_secret.json file. $client->setAuthConfig('client_secret.json'); // Required, to set the scope value, call the addScope function $client->addScope([Google\Service\Drive::DRIVE_METADATA_READONLY, Google\Service\Calendar::CALENDAR_READONLY]); // Required, call the setRedirectUri function to specify a valid redirect URI for the // provided client_id $client->setRedirectUri('http://' . $_SERVER['HTTP_HOST'] . '/oauth2callback.php'); // Recommended, offline access will give you both an access and refresh token so that // your app can refresh the access token without user interaction. $client->setAccessType('offline'); // Recommended, call the setState function. Using a state value can increase your assurance that // an incoming connection is the result of an authentication request. $client->setState($sample_passthrough_value); // Optional, if your application knows which user is trying to authenticate, it can use this // parameter to provide a hint to the Google Authentication Server. $client->setLoginHint('hint@example.com'); // Optional, call the setPrompt function to set "consent" will prompt the user for consent $client->setPrompt('consent'); // Optional, call the setIncludeGrantedScopes function with true to enable incremental // authorization $client->setIncludeGrantedScopes(true);
Питон
Следующий фрагмент кода использует модуль google-auth-oauthlib.flow
для создания запроса на авторизацию.
Код создаёт объект Flow
, который идентифицирует ваше приложение, используя информацию из файла client_secret.json , загруженного после создания учётных данных авторизации . Этот объект также определяет области действия, к которым ваше приложение запрашивает разрешение, и URL-адрес конечной точки авторизации вашего приложения, которая будет обрабатывать ответ от сервера Google OAuth 2.0. Наконец, код задаёт необязательные параметры access_type
и include_granted_scopes
.
Например, этот код запрашивает автономный доступ только для чтения к метаданным Google Диска и событиям Календаря пользователя:
import google.oauth2.credentials import google_auth_oauthlib.flow # Required, call the from_client_secrets_file method to retrieve the client ID from a # client_secret.json file. The client ID (from that file) and access scopes are required. (You can # also use the from_client_config method, which passes the client configuration as it originally # appeared in a client secrets file but doesn't access the file itself.) flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file('client_secret.json', scopes=['https://www.googleapis.com/auth/drive.metadata.readonly', 'https://www.googleapis.com/auth/calendar.readonly']) # Required, indicate where the API server will redirect the user after the user completes # the authorization flow. The redirect URI is required. The value must exactly # match one of the authorized redirect URIs for the OAuth 2.0 client, which you # configured in the API Console. If this value doesn't match an authorized URI, # you will get a 'redirect_uri_mismatch' error. flow.redirect_uri = 'https://www.example.com/oauth2callback' # Generate URL for request to Google's OAuth 2.0 server. # Use kwargs to set optional request parameters. authorization_url, state = flow.authorization_url( # Recommended, enable offline access so that you can refresh an access token without # re-prompting the user for permission. Recommended for web server apps. access_type='offline', # Optional, enable incremental authorization. Recommended as a best practice. include_granted_scopes='true', # Optional, if your application knows which user is trying to authenticate, it can use this # parameter to provide a hint to the Google Authentication Server. login_hint='hint@example.com', # Optional, set prompt to 'consent' will prompt the user for consent prompt='consent')
Руби
Используйте созданный вами файл client_secrets.json для настройки объекта клиента в вашем приложении. При настройке объекта клиента вы указываете области действия, к которым вашему приложению необходимо получить доступ, а также URL-адрес конечной точки аутентификации вашего приложения, которая будет обрабатывать ответ от сервера OAuth 2.0.
Например, этот код запрашивает автономный доступ только для чтения к метаданным Google Диска и событиям Календаря пользователя:
require 'googleauth' require 'googleauth/web_user_authorizer' require 'googleauth/stores/redis_token_store' require 'google/apis/drive_v3' require 'google/apis/calendar_v3' # Required, call the from_file method to retrieve the client ID from a # client_secret.json file. client_id = Google::Auth::ClientId.from_file('/path/to/client_secret.json') # Required, scope value # Access scopes for two non-Sign-In scopes: Read-only Drive activity and Google Calendar. scope = ['Google::Apis::DriveV3::AUTH_DRIVE_METADATA_READONLY', 'Google::Apis::CalendarV3::AUTH_CALENDAR_READONLY'] # Required, Authorizers require a storage instance to manage long term persistence of # access and refresh tokens. token_store = Google::Auth::Stores::RedisTokenStore.new(redis: Redis.new) # Required, indicate where the API server will redirect the user after the user completes # the authorization flow. The redirect URI is required. The value must exactly # match one of the authorized redirect URIs for the OAuth 2.0 client, which you # configured in the API Console. If this value doesn't match an authorized URI, # you will get a 'redirect_uri_mismatch' error. callback_uri = '/oauth2callback' # To use OAuth2 authentication, we need access to a CLIENT_ID, CLIENT_SECRET, AND REDIRECT_URI # from the client_secret.json file. To get these credentials for your application, visit # https://console.cloud.google.com/apis/credentials. authorizer = Google::Auth::WebUserAuthorizer.new(client_id, scope, token_store, callback_uri)
Ваше приложение использует клиентский объект для выполнения операций OAuth 2.0, таких как генерация URL-адресов запросов авторизации и применение токенов доступа к HTTP-запросам.
Node.js
Следующий фрагмент кода создает объект google.auth.OAuth2
, который определяет параметры в запросе авторизации.
Этот объект использует информацию из файла client_secret.json для идентификации вашего приложения. Чтобы запросить у пользователя разрешение на получение токена доступа, перенаправьте его на страницу согласия. Чтобы создать URL-адрес страницы согласия:
const {google} = require('googleapis'); const crypto = require('crypto'); const express = require('express'); const session = require('express-session'); /** * To use OAuth2 authentication, we need access to a CLIENT_ID, CLIENT_SECRET, AND REDIRECT_URI * from the client_secret.json file. To get these credentials for your application, visit * https://console.cloud.google.com/apis/credentials. */ const oauth2Client = new google.auth.OAuth2( YOUR_CLIENT_ID, YOUR_CLIENT_SECRET, YOUR_REDIRECT_URL ); // Access scopes for two non-Sign-In scopes: Read-only Drive activity and Google Calendar. const scopes = [ 'https://www.googleapis.com/auth/drive.metadata.readonly', 'https://www.googleapis.com/auth/calendar.readonly' ]; // Generate a secure random state value. const state = crypto.randomBytes(32).toString('hex'); // Store state in the session req.session.state = state; // Generate a url that asks permissions for the Drive activity and Google Calendar scope const authorizationUrl = oauth2Client.generateAuthUrl({ // 'online' (default) or 'offline' (gets refresh_token) access_type: 'offline', /** Pass in the scopes array defined above. * Alternatively, if only one scope is needed, you can pass a scope URL as a string */ scope: scopes, // Enable incremental authorization. Recommended as a best practice. include_granted_scopes: true, // Include the state parameter to reduce the risk of CSRF attacks. state: state });
Важное примечание : refresh_token
возвращается только при первой авторизации. Подробнее здесь .
HTTP/REST
Конечная точка OAuth 2.0 от Google находится по адресу https://accounts.google.com/o/oauth2/v2/auth
. Эта конечная точка доступна только по протоколу HTTPS. Обычные HTTP-подключения отклоняются.
Сервер авторизации Google поддерживает следующие параметры строки запроса для приложений веб-сервера:
Параметры | |||||||
---|---|---|---|---|---|---|---|
client_id | Необходимый Идентификатор клиента для вашего приложения. Вы можете найти это значение в Cloud ConsoleClients page. | ||||||
redirect_uri | Необходимый Определяет, куда API-сервер перенаправляет пользователя после завершения процесса авторизации. Значение должно точно соответствовать одному из разрешенных URI перенаправления для клиента OAuth 2.0, настроенных в настройках клиента. Cloud ConsoleClients page. Если это значение не соответствует авторизованному URI перенаправления для предоставленного Обратите внимание, что схема | ||||||
response_type | Необходимый Определяет, возвращает ли конечная точка Google OAuth 2.0 код авторизации. Установите значение параметра | ||||||
scope | Необходимый Список областей действия, разделенных пробелами, которые определяют ресурсы, к которым ваше приложение может получить доступ от имени пользователя. Эти значения используются в окне согласия, которое Google отображает пользователю. Области действия позволяют вашему приложению запрашивать доступ только к тем ресурсам, которые ему необходимы, а также позволяют пользователям контролировать объём предоставляемого им доступа. Таким образом, существует обратная зависимость между количеством запрашиваемых областей действия и вероятностью получения согласия пользователя. Мы рекомендуем вашему приложению запрашивать доступ к областям авторизации в контексте, когда это возможно. Запрашивая доступ к пользовательским данным в контексте, используя инкрементальную авторизацию , вы помогаете пользователям понять, зачем вашему приложению нужен запрашиваемый доступ. | ||||||
access_type | Рекомендуется Указывает, может ли ваше приложение обновлять токены доступа, когда пользователь отсутствует в браузере. Допустимые значения параметра: Установите значение « | ||||||
state | Рекомендуется Указывает любое строковое значение, которое ваше приложение использует для сохранения состояния между вашим запросом авторизации и ответом сервера авторизации. Сервер возвращает точное значение, которое вы отправляете в виде пары Этот параметр можно использовать для различных целей, например, для перенаправления пользователя на нужный ресурс в приложении, отправки одноразовых кодов и предотвращения подделки межсайтовых запросов. Поскольку | ||||||
include_granted_scopes | Необязательный Позволяет приложениям использовать инкрементальную авторизацию для запроса доступа к дополнительным областям в контексте. Если этому параметру присвоено значение | ||||||
enable_granular_consent | Необязательный Значение по умолчанию — Когда Google включит детальные разрешения для приложения, этот параметр больше не будет иметь никакого эффекта. | ||||||
login_hint | Необязательный Если ваше приложение знает, какой пользователь пытается пройти аутентификацию, оно может использовать этот параметр для предоставления подсказки серверу аутентификации Google. Сервер использует подсказку для упрощения процесса входа, либо предварительно заполняя поле адреса электронной почты в форме входа, либо выбирая подходящий сеанс множественного входа. Задайте в качестве значения параметра адрес электронной почты или | ||||||
prompt | Необязательный Список запросов, разделенных пробелами и чувствительных к регистру, для отображения пользователю. Если этот параметр не указан, запрос будет выведен только при первом запросе доступа вашим проектом. Подробнее см. в разделе Запрос повторного согласия . Возможные значения:
|
Шаг 2: Перенаправление на сервер OAuth 2.0 Google
Перенаправление пользователя на сервер OAuth 2.0 Google для инициирования процесса аутентификации и авторизации. Обычно это происходит, когда приложению впервые требуется доступ к данным пользователя. В случае инкрементальной авторизации этот шаг также происходит, когда приложению впервые требуется доступ к дополнительным ресурсам, на доступ к которым у него пока нет разрешения.
PHP
- Создайте URL-адрес для запроса доступа с сервера Google OAuth 2.0:
$auth_url = $client->createAuthUrl();
- Перенаправить пользователя на
$auth_url
:header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
Питон
В этом примере показано, как перенаправить пользователя на URL-адрес авторизации с помощью фреймворка веб-приложений Flask:
return flask.redirect(authorization_url)
Руби
- Создайте URL-адрес для запроса доступа с сервера Google OAuth 2.0:
auth_uri = authorizer.get_authorization_url(request: request)
- Перенаправить пользователя на
auth_uri
.
Node.js
- Используйте сгенерированный URL
authorizationUrl
из шага 1 методаgenerateAuthUrl
для запроса доступа с сервера OAuth 2.0 Google. - Перенаправить пользователя на
authorizationUrl
.res.redirect(authorizationUrl);
HTTP/REST
Пример перенаправления на сервер авторизации Google
Пример URL-адреса показан ниже с переносами строк и пробелами для удобства чтения.
https://accounts.google.com/o/oauth2/v2/auth? scope=https%3A//www.googleapis.com/auth/drive.metadata.readonly%20https%3A//www.googleapis.com/auth/calendar.readonly& access_type=offline& include_granted_scopes=true& response_type=code& state=state_parameter_passthrough_value& redirect_uri=https%3A//oauth2.example.com/code& client_id=client_id
После создания URL-адреса запроса перенаправьте на него пользователя.
Сервер Google OAuth 2.0 аутентифицирует пользователя и получает его согласие на доступ вашего приложения к запрошенным областям. Ответ отправляется обратно в ваше приложение по указанному вами URL-адресу перенаправления.
Шаг 3: Google запрашивает согласие пользователя
На этом этапе пользователь решает, предоставлять ли вашему приложению запрошенный доступ. На этом этапе Google отображает окно согласия, в котором указано название вашего приложения и сервисы Google API, к которым оно запрашивает разрешение, а также учётные данные пользователя и список областей доступа, которые необходимо предоставить. Пользователь может дать согласие на предоставление доступа к одной или нескольким областям доступа, запрошенным вашим приложением, или отклонить запрос.
На этом этапе вашему приложению не нужно ничего делать, так как оно ожидает ответа от сервера Google OAuth 2.0 о предоставлении доступа. Этот ответ поясняется на следующем шаге.
Ошибки
Запросы к конечной точке авторизации Google OAuth 2.0 могут отображать сообщения об ошибках вместо ожидаемых процессов аутентификации и авторизации. Распространенные коды ошибок и рекомендуемые решения:
admin_policy_enforced
Учётная запись Google не может авторизовать одну или несколько запрошенных областей действия из-за политик администратора Google Workspace. Подробнее о том, как администратор может ограничить доступ ко всем областям действия или к конфиденциальным и ограниченным областям действия, пока доступ не будет явно предоставлен вашему идентификатору клиента OAuth, см. в справочной статье Google Workspace Управление доступом сторонних и внутренних приложений к данным Google Workspace .
disallowed_useragent
Конечная точка авторизации отображается внутри встроенного пользовательского агента, запрещенного политиками Google OAuth 2.0 .
Разработчики приложений для iOS и macOS могут столкнуться с этой ошибкой при открытии запросов на авторизацию в WKWebView
. Вместо этого разработчикам следует использовать библиотеки iOS, такие как Google Sign-In для iOS или AppAuth от OpenID Foundation для iOS .
Веб-разработчики могут столкнуться с этой ошибкой, когда приложение iOS или macOS открывает общую веб-ссылку во встроенном пользовательском агенте, а пользователь переходит с вашего сайта на конечную точку авторизации Google OAuth 2.0. Разработчикам следует разрешить открытие общих ссылок в обработчике ссылок по умолчанию операционной системы, который включает как обработчики универсальных ссылок , так и приложение браузера по умолчанию. Библиотека SFSafariViewController
также поддерживается.
org_internal
Идентификатор клиента OAuth в запросе является частью проекта, ограничивающего доступ к аккаунтам Google в конкретной организации Google Cloud . Подробнее об этом параметре конфигурации см. в разделе «Тип пользователя» справочной статьи «Настройка экрана согласия OAuth».
invalid_client
Неверный секретный ключ клиента OAuth. Проверьте конфигурацию клиента OAuth , включая идентификатор клиента и секретный ключ, использованные для этого запроса.
deleted_client
Клиент OAuth, использованный для выполнения запроса, был удалён. Удаление может быть выполнено вручную или автоматически в случае неиспользуемых клиентов . Удалённые клиенты могут быть восстановлены в течение 30 дней с момента удаления. Подробнее .
invalid_grant
При обновлении токена доступа или использовании инкрементальной авторизации срок действия токена мог истечь или он мог быть аннулирован. Повторно аутентифицируйте пользователя и запросите его согласие на получение новых токенов. Если эта ошибка продолжает появляться, убедитесь, что ваше приложение настроено правильно и вы используете правильные токены и параметры в запросе. В противном случае учётная запись пользователя могла быть удалена или отключена.
redirect_uri_mismatch
redirect_uri
переданный в запросе авторизации, не соответствует авторизованному URI перенаправления для идентификатора клиента OAuth. Проверьте авторизованные URI перенаправления в Google Cloud ConsoleClients page.
Параметр redirect_uri
может ссылаться на внеполосный (OOB) поток OAuth, который устарел и больше не поддерживается. Чтобы обновить интеграцию, обратитесь к руководству по миграции .
invalid_request
С вашим запросом возникла ошибка. Это может быть связано с рядом причин:
- Запрос не был правильно отформатирован.
- В запросе отсутствовали обязательные параметры.
- Запрос использует метод авторизации, который Google не поддерживает. Убедитесь, что ваша интеграция OAuth использует рекомендуемый метод.
Шаг 4: Обработка ответа сервера OAuth 2.0
Сервер OAuth 2.0 отвечает на запрос доступа вашего приложения, используя URL-адрес, указанный в запросе.
Если пользователь одобряет запрос на доступ, ответ содержит код авторизации. Если пользователь не одобряет запрос, ответ содержит сообщение об ошибке. Код авторизации или сообщение об ошибке, возвращаемое веб-серверу, отображается в строке запроса, как показано ниже:
Ответ об ошибке:
https://oauth2.example.com/auth?error=access_denied
Ответ кода авторизации:
https://oauth2.example.com/auth?code=4/P7q7W91a-oMsCeLvIaQm6bTrgtp7
Пример ответа сервера OAuth 2.0
Вы можете протестировать этот процесс, нажав на следующий пример URL-адреса, который запрашивает доступ только для чтения для просмотра метаданных файлов на вашем Google Диске и доступ только для чтения для просмотра событий вашего Google Календаря:
https://accounts.google.com/o/oauth2/v2/auth? scope=https%3A//www.googleapis.com/auth/drive.metadata.readonly%20https%3A//www.googleapis.com/auth/calendar.readonly& access_type=offline& include_granted_scopes=true& response_type=code& state=state_parameter_passthrough_value& redirect_uri=https%3A//oauth2.example.com/code& client_id=client_id
После завершения процесса OAuth 2.0 вы будете перенаправлены на http://localhost/oauth2callback
, что, скорее всего, приведёт к ошибке 404 NOT FOUND
если только ваш локальный компьютер не обслуживает файл по этому адресу. Следующий шаг предоставляет более подробную информацию об информации, возвращаемой в URI при перенаправлении пользователя обратно в ваше приложение.
Шаг 5: Обмен кода авторизации на токены обновления и доступа
После того как веб-сервер получит код авторизации, он может обменять код авторизации на токен доступа.
PHP
Для обмена кода авторизации на токен доступа используйте метод fetchAccessTokenWithAuthCode
:
$access_token = $client->fetchAccessTokenWithAuthCode($_GET['code']);
Питон
На странице обратного вызова используйте библиотеку google-auth
для проверки ответа сервера авторизации. Затем используйте метод flow.fetch_token
для обмена кода авторизации в этом ответе на токен доступа:
state = flask.session['state'] flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file( 'client_secret.json', scopes=['https://www.googleapis.com/auth/drive.metadata.readonly'], state=state) flow.redirect_uri = flask.url_for('oauth2callback', _external=True) authorization_response = flask.request.url flow.fetch_token(authorization_response=authorization_response) # Store the credentials in browser session storage, but for security: client_id, client_secret, # and token_uri are instead stored only on the backend server. credentials = flow.credentials flask.session['credentials'] = { 'token': credentials.token, 'refresh_token': credentials.refresh_token, 'granted_scopes': credentials.granted_scopes}
Руби
На странице обратного вызова используйте библиотеку googleauth
для проверки ответа сервера авторизации. Используйте метод authorizer.handle_auth_callback_deferred
для сохранения кода авторизации и перенаправления на URL-адрес, с которого изначально была запрошена авторизация. Это откладывает передачу кода, временно сохраняя результаты в сеансе пользователя.
target_url = Google::Auth::WebUserAuthorizer.handle_auth_callback_deferred(request) redirect target_url
Node.js
Для обмена кода авторизации на токен доступа используйте метод getToken
:
const url = require('url'); // Receive the callback from Google's OAuth 2.0 server. app.get('/oauth2callback', async (req, res) => { let q = url.parse(req.url, true).query; if (q.error) { // An error response e.g. error=access_denied console.log('Error:' + q.error); } else if (q.state !== req.session.state) { //check state value console.log('State mismatch. Possible CSRF attack'); res.end('State mismatch. Possible CSRF attack'); } else { // Get access and refresh tokens (if access_type is offline) let { tokens } = await oauth2Client.getToken(q.code); oauth2Client.setCredentials(tokens); });
HTTP/REST
Чтобы обменять код авторизации на токен доступа, вызовите конечную точку https://oauth2.googleapis.com/token
и задайте следующие параметры:
Поля | |
---|---|
client_id | Идентификатор клиента, полученный из Cloud ConsoleClients page. |
client_secret | Секрет клиента, полученный от Cloud ConsoleClients page. |
code | Код авторизации, возвращенный из первоначального запроса. |
grant_type | Как определено в спецификации OAuth 2.0 , значение этого поля должно быть установлено на authorization_code . |
redirect_uri | Один из URI перенаправления, перечисленных для вашего проекта в Cloud ConsoleClients page для заданного client_id . |
В следующем фрагменте показан пример запроса:
POST /token HTTP/1.1 Host: oauth2.googleapis.com Content-Type: application/x-www-form-urlencoded code=4/P7q7W91a-oMsCeLvIaQm6bTrgtp7& client_id=your_client_id& client_secret=your_client_secret& redirect_uri=https%3A//oauth2.example.com/code& grant_type=authorization_code
Google отвечает на этот запрос, возвращая JSON-объект, содержащий краткосрочный токен доступа и токен обновления. Обратите внимание, что токен обновления возвращается только в том случае, если ваше приложение установило параметр access_type
на offline
в первоначальном запросе к серверу авторизации Google .
Ответ содержит следующие поля:
Поля | |
---|---|
access_token | Токен, который ваше приложение отправляет для авторизации запроса API Google. |
expires_in | Оставшееся время жизни токена доступа в секундах. |
refresh_token | Токен, который можно использовать для получения нового токена доступа. Токены обновления действительны до тех пор, пока пользователь не отзовёт доступ или не истечёт срок действия токена обновления. Опять же, это поле присутствует в данном ответе только в том случае, если в первоначальном запросе к серверу авторизации Google параметру access_type задано значение offline . |
refresh_token_expires_in | Оставшееся время жизни токена обновления в секундах. Это значение устанавливается только в том случае, если пользователь предоставляет доступ с ограничением по времени . |
scope | Области доступа, предоставляемые access_token , выраженные в виде списка строк, разделенных пробелами и чувствительных к регистру. |
token_type | Тип возвращаемого токена. В настоящее время значение этого поля всегда равно Bearer . |
В следующем фрагменте показан пример ответа:
{ "access_token": "1/fFAGRNJru1FTz70BzhT3Zg", "expires_in": 3920, "token_type": "Bearer", "scope": "https://www.googleapis.com/auth/drive.metadata.readonly https://www.googleapis.com/auth/calendar.readonly", "refresh_token": "1//xEoDL4iW3cxlI7yDbSRFYNG01kVKM2C-259HOF2aQbI" }
Ошибки
При обмене кода авторизации на токен доступа вместо ожидаемого ответа может возникнуть следующая ошибка. Ниже перечислены распространённые коды ошибок и рекомендуемые способы их устранения.
invalid_grant
Предоставленный код авторизации недействителен или имеет неправильный формат. Запросите новый код, перезапустив процесс OAuth, чтобы снова запросить согласие пользователя.
Шаг 6: Проверьте, какие области действия предоставлены пользователями
При запросе нескольких разрешений (областей действия) пользователи могут не предоставить вашему приложению доступ ко всем из них. Ваше приложение должно проверять, какие области действия были фактически предоставлены, и корректно обрабатывать ситуации, когда некоторые разрешения отклонены, обычно путём отключения функций, зависящих от этих отклоненных областей действия.
Однако есть исключения. Приложения Google Workspace Enterprise с делегированием полномочий на уровне домена или приложения, помеченные как «Доверенные» , обходят экран согласия на детализированные разрешения. В таких приложениях пользователи не увидят экран согласия на детализированные разрешения. Вместо этого ваше приложение либо получит все запрошенные области действия, либо не получит ни одной.
Более подробную информацию см. в разделе Как обрабатывать детализированные разрешения .
PHP
Чтобы проверить, какие области действия предоставил пользователь, используйте метод getGrantedScope()
:
// Space-separated string of granted scopes if it exists, otherwise null. $granted_scopes = $client->getOAuth2Service()->getGrantedScope(); // Determine which scopes user granted and build a dictionary $granted_scopes_dict = [ 'Drive' => str_contains($granted_scopes, Google\Service\Drive::DRIVE_METADATA_READONLY), 'Calendar' => str_contains($granted_scopes, Google\Service\Calendar::CALENDAR_READONLY) ];
Питон
Возвращенный объект credentials
имеет свойство granted_scopes
, которое представляет собой список областей, которые пользователь предоставил вашему приложению.
credentials = flow.credentials flask.session['credentials'] = { 'token': credentials.token, 'refresh_token': credentials.refresh_token, 'granted_scopes': credentials.granted_scopes}
Следующая функция проверяет, какие области действия пользователь предоставил вашему приложению.
def check_granted_scopes(credentials): features = {} if 'https://www.googleapis.com/auth/drive.metadata.readonly' in credentials['granted_scopes']: features['drive'] = True else: features['drive'] = False if 'https://www.googleapis.com/auth/calendar.readonly' in credentials['granted_scopes']: features['calendar'] = True else: features['calendar'] = False return features
Руби
При запросе нескольких областей одновременно проверьте, какие области были предоставлены через свойство scope
действия объекта credentials
.
# User authorized the request. Now, check which scopes were granted. if credentials.scope.include?(Google::Apis::DriveV3::AUTH_DRIVE_METADATA_READONLY) # User authorized read-only Drive activity permission. # Calling the APIs, etc else # User didn't authorize read-only Drive activity permission. # Update UX and application accordingly end # Check if user authorized Calendar read permission. if credentials.scope.include?(Google::Apis::CalendarV3::AUTH_CALENDAR_READONLY) # User authorized Calendar read permission. # Calling the APIs, etc. else # User didn't authorize Calendar read permission. # Update UX and application accordingly end
Node.js
При запросе нескольких областей одновременно проверьте, какие области были предоставлены через свойство scope
действия объекта tokens
.
// User authorized the request. Now, check which scopes were granted. if (tokens.scope.includes('https://www.googleapis.com/auth/drive.metadata.readonly')) { // User authorized read-only Drive activity permission. // Calling the APIs, etc. } else { // User didn't authorize read-only Drive activity permission. // Update UX and application accordingly } // Check if user authorized Calendar read permission. if (tokens.scope.includes('https://www.googleapis.com/auth/calendar.readonly')) { // User authorized Calendar read permission. // Calling the APIs, etc. } else { // User didn't authorize Calendar read permission. // Update UX and application accordingly }
HTTP/REST
Чтобы проверить, предоставил ли пользователь вашему приложению доступ к определённой области действия, проверьте поле scope
в ответе токена доступа. Области действия, предоставляемые токеном доступа, представлены в виде списка строк, разделённых пробелами и чувствительных к регистру.
Например, следующий пример ответа токена доступа указывает, что пользователь предоставил вашему приложению доступ только для чтения к действиям Диска и событиям Календаря:
{ "access_token": "1/fFAGRNJru1FTz70BzhT3Zg", "expires_in": 3920, "token_type": "Bearer", "scope": "https://www.googleapis.com/auth/drive.metadata.readonly https://www.googleapis.com/auth/calendar.readonly", "refresh_token": "1//xEoDL4iW3cxlI7yDbSRFYNG01kVKM2C-259HOF2aQbI" }
Вызов API Google
PHP
Используйте токен доступа для вызова API Google, выполнив следующие шаги:
- Если вам необходимо применить токен доступа к новому объекту
Google\Client
— например, если вы сохранили токен доступа в сеансе пользователя — используйте методsetAccessToken
:$client->setAccessToken($access_token);
- Создайте объект службы для API, который вы хотите вызвать. Для создания объекта службы необходимо предоставить авторизованный объект
Google\Client
конструктору API, который вы хотите вызвать. Например, для вызова API Диска:$drive = new Google\Service\Drive($client);
- Выполняйте запросы к API-сервису, используя интерфейс, предоставляемый объектом сервиса . Например, чтобы получить список файлов на Google Диске аутентифицированного пользователя:
$files = $drive->files->listFiles(array());
Питон
Получив токен доступа, ваше приложение сможет использовать его для авторизации API-запросов от имени определённой учётной записи пользователя или сервиса. Используйте учётные данные, специфичные для пользователя, для создания объекта сервиса для API, который вы хотите вызвать, а затем используйте этот объект для выполнения авторизованных API-запросов.
- Создайте объект службы для API, который вы хотите вызвать. Для создания объекта службы вызовите метод
build
библиотекиgoogleapiclient.discovery
, указав имя и версию API, а также учётные данные пользователя. Например, для вызова версии 3 API Диска:from googleapiclient.discovery import build drive = build('drive', 'v2', credentials=credentials)
- Выполняйте запросы к API-сервису, используя интерфейс, предоставляемый объектом сервиса . Например, чтобы получить список файлов на Google Диске аутентифицированного пользователя:
files = drive.files().list().execute()
Руби
Получив токен доступа, ваше приложение сможет использовать его для выполнения API-запросов от имени определённой учётной записи пользователя или сервиса. Используйте учётные данные пользователя для создания объекта сервиса для API, который вы хотите вызвать, а затем используйте этот объект для выполнения авторизованных API-запросов.
- Создайте объект службы для API, который вы хотите вызвать. Например, для вызова версии 3 API Диска:
drive = Google::Apis::DriveV3::DriveService.new
- Установите учетные данные на сервисе:
drive.authorization = credentials
- Выполняйте запросы к API-сервису, используя интерфейс, предоставляемый объектом сервиса . Например, чтобы получить список файлов на Google Диске аутентифицированного пользователя:
files = drive.list_files
Альтернативно, авторизацию можно предоставить на уровне метода, указав параметр options
для метода:
files = drive.list_files(options: { authorization: credentials })
Node.js
Получив токен доступа и присвоив его объекту OAuth2
, используйте этот объект для вызова API Google. Ваше приложение может использовать этот токен для авторизации запросов API от имени определённой учётной записи пользователя или учётной записи сервиса. Создайте объект сервиса для API, который вы хотите вызвать. Например, следующий код использует API Google Диска для вывода списка имён файлов на Диске пользователя.
const { google } = require('googleapis'); // Example of using Google Drive API to list filenames in user's Drive. const drive = google.drive('v3'); drive.files.list({ auth: oauth2Client, pageSize: 10, fields: 'nextPageToken, files(id, name)', }, (err1, res1) => { if (err1) return console.log('The API returned an error: ' + err1); const files = res1.data.files; if (files.length) { console.log('Files:'); files.map((file) => { console.log(`${file.name} (${file.id})`); }); } else { console.log('No files found.'); } });
HTTP/REST
After your application obtains an access token, you can use the token to make calls to a Google API on behalf of a given user account if the scope(s) of access required by the API have been granted. To do this, include the access token in a request to the API by including either an access_token
query parameter or an Authorization
HTTP header Bearer
value. When possible, the HTTP header is preferable, because query strings tend to be visible in server logs. In most cases you can use a client library to set up your calls to Google APIs (for example, when calling the Drive Files API ).
You can try out all the Google APIs and view their scopes at the OAuth 2.0 Playground .
HTTP GET examples
A call to the drive.files
endpoint (the Drive Files API) using the Authorization: Bearer
HTTP header might look like the following. Note that you need to specify your own access token:
GET /drive/v2/files HTTP/1.1 Host: www.googleapis.com Authorization: Bearer access_token
Here is a call to the same API for the authenticated user using the access_token
query string parameter:
GET https://www.googleapis.com/drive/v2/files?access_token=access_token
curl
examples
You can test these commands with the curl
command-line application. Here's an example that uses the HTTP header option (preferred):
curl -H "Authorization: Bearer access_token" https://www.googleapis.com/drive/v2/files
Or, alternatively, the query string parameter option:
curl https://www.googleapis.com/drive/v2/files?access_token=access_token
Complete example
The following example prints a JSON-formatted list of files in a user's Google Drive after the user authenticates and gives consent for the application to access the user's Drive metadata.
PHP
To run this example:
- В API Console, add the URL of the local machine to the list of redirect URLs. For example, add
http://localhost:8080
. - Create a new directory and change to it. For example:
mkdir ~/php-oauth2-example cd ~/php-oauth2-example
- Install the Google API Client Library for PHP using Composer :
composer require google/apiclient:^2.15.0
- Create the files
index.php
andoauth2callback.php
with the following content. - Run the example with the PHP's built-in test web server:
php -S localhost:8080 ~/php-oauth2-example
index.php
<?php require_once __DIR__.'/vendor/autoload.php'; session_start(); $client = new Google\Client(); $client->setAuthConfig('client_secret.json'); // User granted permission as an access token is in the session. if (isset($_SESSION['access_token']) && $_SESSION['access_token']) { $client->setAccessToken($_SESSION['access_token']); // Check if user granted Drive permission if ($_SESSION['granted_scopes_dict']['Drive']) { echo "Drive feature is enabled."; echo "</br>"; $drive = new Drive($client); $files = array(); $response = $drive->files->listFiles(array()); foreach ($response->files as $file) { echo "File: " . $file->name . " (" . $file->id . ")"; echo "</br>"; } } else { echo "Drive feature is NOT enabled."; echo "</br>"; } // Check if user granted Calendar permission if ($_SESSION['granted_scopes_dict']['Calendar']) { echo "Calendar feature is enabled."; echo "</br>"; } else { echo "Calendar feature is NOT enabled."; echo "</br>"; } } else { // Redirect users to outh2call.php which redirects users to Google OAuth 2.0 $redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/oauth2callback.php'; header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL)); } ?>
oauth2callback.php
<?php require_once __DIR__.'/vendor/autoload.php'; session_start(); $client = new Google\Client(); // Required, call the setAuthConfig function to load authorization credentials from // client_secret.json file. $client->setAuthConfigFile('client_secret.json'); $client->setRedirectUri('http://' . $_SERVER['HTTP_HOST']. $_SERVER['PHP_SELF']); // Required, to set the scope value, call the addScope function. $client->addScope([Google\Service\Drive::DRIVE_METADATA_READONLY, Google\Service\Calendar::CALENDAR_READONLY]); // Enable incremental authorization. Recommended as a best practice. $client->setIncludeGrantedScopes(true); // Recommended, offline access will give you both an access and refresh token so that // your app can refresh the access token without user interaction. $client->setAccessType("offline"); // Generate a URL for authorization as it doesn't contain code and error if (!isset($_GET['code']) && !isset($_GET['error'])) { // Generate and set state value $state = bin2hex(random_bytes(16)); $client->setState($state); $_SESSION['state'] = $state; // Generate a url that asks permissions. $auth_url = $client->createAuthUrl(); header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL)); } // User authorized the request and authorization code is returned to exchange access and // refresh tokens. if (isset($_GET['code'])) { // Check the state value if (!isset($_GET['state']) || $_GET['state'] !== $_SESSION['state']) { die('State mismatch. Possible CSRF attack.'); } // Get access and refresh tokens (if access_type is offline) $token = $client->fetchAccessTokenWithAuthCode($_GET['code']); /** Save access and refresh token to the session variables. * ACTION ITEM: In a production app, you likely want to save the * refresh token in a secure persistent storage instead. */ $_SESSION['access_token'] = $token; $_SESSION['refresh_token'] = $client->getRefreshToken(); // Space-separated string of granted scopes if it exists, otherwise null. $granted_scopes = $client->getOAuth2Service()->getGrantedScope(); // Determine which scopes user granted and build a dictionary $granted_scopes_dict = [ 'Drive' => str_contains($granted_scopes, Google\Service\Drive::DRIVE_METADATA_READONLY), 'Calendar' => str_contains($granted_scopes, Google\Service\Calendar::CALENDAR_READONLY) ]; $_SESSION['granted_scopes_dict'] = $granted_scopes_dict; $redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/'; header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL)); } // An error response e.g. error=access_denied if (isset($_GET['error'])) { echo "Error: ". $_GET['error']; } ?>
Питон
This example uses the Flask framework. It runs a web application at http://localhost:8080
that lets you test the OAuth 2.0 flow. If you go to that URL, you should see five links:
- Call Drive API: This link points to a page that tries to execute a sample API request if users granted the permission. If necessary, it starts the authorization flow. If successful, the page displays the API response.
- Mock page to call Calendar API: This link points to a maockpage that tries to execute a sample Calendar API request if users granted the permission. If necessary, it starts the authorization flow. If successful, the page displays the API response.
- Test the auth flow directly: This link points to a page that tries to send the user through the authorization flow . The app requests permission to submit authorized API requests on the user's behalf.
- Revoke current credentials: This link points to a page that revokes permissions that the user has already granted to the application.
- Clear Flask session credentials: This link clears authorization credentials that are stored in the Flask session. This lets you see what would happen if a user who had already granted permission to your app tried to execute an API request in a new session. It also lets you see the API response your app would get if a user had revoked permissions granted to your app, and your app still tried to authorize a request with a revoked access token.
# -*- coding: utf-8 -*- import os import flask import json import requests import google.oauth2.credentials import google_auth_oauthlib.flow import googleapiclient.discovery # This variable specifies the name of a file that contains the OAuth 2.0 # information for this application, including its client_id and client_secret. CLIENT_SECRETS_FILE = "client_secret.json" # The OAuth 2.0 access scope allows for access to the # authenticated user's account and requires requests to use an SSL connection. SCOPES = ['https://www.googleapis.com/auth/drive.metadata.readonly', 'https://www.googleapis.com/auth/calendar.readonly'] API_SERVICE_NAME = 'drive' API_VERSION = 'v2' app = flask.Flask(__name__) # Note: A secret key is included in the sample so that it works. # If you use this code in your application, replace this with a truly secret # key. See https://flask.palletsprojects.com/quickstart/#sessions. app.secret_key = 'REPLACE ME - this value is here as a placeholder.' @app.route('/') def index(): return print_index_table() @app.route('/drive') def drive_api_request(): if 'credentials' not in flask.session: return flask.redirect('authorize') features = flask.session['features'] if features['drive']: # Load client secrets from the server-side file. with open(CLIENT_SECRETS_FILE, 'r') as f: client_config = json.load(f)['web'] # Load user-specific credentials from browser session storage. session_credentials = flask.session['credentials'] # Reconstruct the credentials object. credentials = google.oauth2.credentials.Credentials( refresh_token=session_credentials.get('refresh_token'), scopes=session_credentials.get('granted_scopes'), token=session_credentials.get('token'), client_id=client_config.get('client_id'), client_secret=client_config.get('client_secret'), token_uri=client_config.get('token_uri')) drive = googleapiclient.discovery.build( API_SERVICE_NAME, API_VERSION, credentials=credentials) files = drive.files().list().execute() # Save credentials back to session in case access token was refreshed. flask.session['credentials'] = credentials_to_dict(credentials) return flask.jsonify(**files) else: # User didn't authorize read-only Drive activity permission. return '<p>Drive feature is not enabled.</p>' @app.route('/calendar') def calendar_api_request(): if 'credentials' not in flask.session: return flask.redirect('authorize') features = flask.session['features'] if features['calendar']: # User authorized Calendar read permission. # Calling the APIs, etc. return ('<p>User granted the Google Calendar read permission. '+ 'This sample code does not include code to call Calendar</p>') else: # User didn't authorize Calendar read permission. # Update UX and application accordingly return '<p>Calendar feature is not enabled.</p>' @app.route('/authorize') def authorize(): # Create flow instance to manage the OAuth 2.0 Authorization Grant Flow steps. flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file( CLIENT_SECRETS_FILE, scopes=SCOPES) # The URI created here must exactly match one of the authorized redirect URIs # for the OAuth 2.0 client, which you configured in the API Console. If this # value doesn't match an authorized URI, you will get a 'redirect_uri_mismatch' # error. flow.redirect_uri = flask.url_for('oauth2callback', _external=True) authorization_url, state = flow.authorization_url( # Enable offline access so that you can refresh an access token without # re-prompting the user for permission. Recommended for web server apps. access_type='offline', # Enable incremental authorization. Recommended as a best practice. include_granted_scopes='true') # Store the state so the callback can verify the auth server response. flask.session['state'] = state return flask.redirect(authorization_url) @app.route('/oauth2callback') def oauth2callback(): # Specify the state when creating the flow in the callback so that it can # verified in the authorization server response. state = flask.session['state'] flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file( CLIENT_SECRETS_FILE, scopes=SCOPES, state=state) flow.redirect_uri = flask.url_for('oauth2callback', _external=True) # Use the authorization server's response to fetch the OAuth 2.0 tokens. authorization_response = flask.request.url flow.fetch_token(authorization_response=authorization_response) # Store credentials in the session. # ACTION ITEM: In a production app, you likely want to save these # credentials in a persistent database instead. credentials = flow.credentials credentials = credentials_to_dict(credentials) flask.session['credentials'] = credentials # Check which scopes user granted features = check_granted_scopes(credentials) flask.session['features'] = features return flask.redirect('/') @app.route('/revoke') def revoke(): if 'credentials' not in flask.session: return ('You need to <a href="/authorize">authorize</a> before ' + 'testing the code to revoke credentials.') # Load client secrets from the server-side file. with open(CLIENT_SECRETS_FILE, 'r') as f: client_config = json.load(f)['web'] # Load user-specific credentials from the session. session_credentials = flask.session['credentials'] # Reconstruct the credentials object. credentials = google.oauth2.credentials.Credentials( refresh_token=session_credentials.get('refresh_token'), scopes=session_credentials.get('granted_scopes'), token=session_credentials.get('token'), client_id=client_config.get('client_id'), client_secret=client_config.get('client_secret'), token_uri=client_config.get('token_uri')) revoke = requests.post('https://oauth2.googleapis.com/revoke', params={'token': credentials.token}, headers = {'content-type': 'application/x-www-form-urlencoded'}) status_code = getattr(revoke, 'status_code') if status_code == 200: # Clear the user's session credentials after successful revocation if 'credentials' in flask.session: del flask.session['credentials'] del flask.session['features'] return('Credentials successfully revoked.' + print_index_table()) else: return('An error occurred.' + print_index_table()) @app.route('/clear') def clear_credentials(): if 'credentials' in flask.session: del flask.session['credentials'] return ('Credentials have been cleared.<br><br>' + print_index_table()) def credentials_to_dict(credentials): return {'token': credentials.token, 'refresh_token': credentials.refresh_token, 'granted_scopes': credentials.granted_scopes} def check_granted_scopes(credentials): features = {} if 'https://www.googleapis.com/auth/drive.metadata.readonly' in credentials['granted_scopes']: features['drive'] = True else: features['drive'] = False if 'https://www.googleapis.com/auth/calendar.readonly' in credentials['granted_scopes']: features['calendar'] = True else: features['calendar'] = False return features def print_index_table(): return ('<table>' + '<tr><td><a href="/authorize">Test the auth flow directly</a></td>' + '<td>Go directly to the authorization flow. If there are stored ' + ' credentials, you still might not be prompted to reauthorize ' + ' the application.</td></tr>' + '<tr><td><a href="/drive">Call Drive API directly</a></td>' + '<td> Use stored credentials to call the API, you still might not be prompted to reauthorize ' + ' the application.</td></tr>' + '<tr><td><a href="/calendar">Call Calendar API directly</a></td>' + '<td> Use stored credentials to call the API, you still might not be prompted to reauthorize ' + ' the application.</td></tr>' + '<tr><td><a href="/revoke">Revoke current credentials</a></td>' + '<td>Revoke the access token associated with the current user ' + ' session. After revoking credentials, if you go to the test ' + ' page, you should see an <code>invalid_grant</code> error.' + '</td></tr>' + '<tr><td><a href="/clear">Clear Flask session credentials</a></td>' + '<td>Clear the access token currently stored in the user session. ' + ' After clearing the token, if you <a href="/authorize">authorize</a> ' + ' again, you should go back to the auth flow.' + '</td></tr></table>') if __name__ == '__main__': # When running locally, disable OAuthlib's HTTPs verification. # ACTION ITEM for developers: # When running in production *do not* leave this option enabled. os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1' # This disables the requested scopes and granted scopes check. # If users only grant partial request, the warning would not be thrown. os.environ['OAUTHLIB_RELAX_TOKEN_SCOPE'] = '1' # Specify a hostname and port that are set as a valid redirect URI # for your API project in the Google API Console. app.run('localhost', 8080, debug=True)
Руби
This example uses the Sinatra framework.
require 'googleauth' require 'googleauth/web_user_authorizer' require 'googleauth/stores/redis_token_store' require 'google/apis/drive_v3' require 'google/apis/calendar_v3' require 'sinatra' configure do enable :sessions # Required, call the from_file method to retrieve the client ID from a # client_secret.json file. set :client_id, Google::Auth::ClientId.from_file('/path/to/client_secret.json') # Required, scope value # Access scopes for two non-Sign-In scopes: Read-only Drive activity and Google Calendar. scope = ['Google::Apis::DriveV3::AUTH_DRIVE_METADATA_READONLY', 'Google::Apis::CalendarV3::AUTH_CALENDAR_READONLY'] # Required, Authorizers require a storage instance to manage long term persistence of # access and refresh tokens. set :token_store, Google::Auth::Stores::RedisTokenStore.new(redis: Redis.new) # Required, indicate where the API server will redirect the user after the user completes # the authorization flow. The redirect URI is required. The value must exactly # match one of the authorized redirect URIs for the OAuth 2.0 client, which you # configured in the API Console. If this value doesn't match an authorized URI, # you will get a 'redirect_uri_mismatch' error. set :callback_uri, '/oauth2callback' # To use OAuth2 authentication, we need access to a CLIENT_ID, CLIENT_SECRET, AND REDIRECT_URI # from the client_secret.json file. To get these credentials for your application, visit # https://console.cloud.google.com/apis/credentials. set :authorizer, Google::Auth::WebUserAuthorizer.new(settings.client_id, settings.scope, settings.token_store, callback_uri: settings.callback_uri) end get '/' do # NOTE: Assumes the user is already authenticated to the app user_id = request.session['user_id'] # Fetch stored credentials for the user from the given request session. # nil if none present credentials = settings.authorizer.get_credentials(user_id, request) if credentials.nil? # Generate a url that asks the user to authorize requested scope(s). # Then, redirect user to the url. redirect settings.authorizer.get_authorization_url(request: request) end # User authorized the request. Now, check which scopes were granted. if credentials.scope.include?(Google::Apis::DriveV3::AUTH_DRIVE_METADATA_READONLY) # User authorized read-only Drive activity permission. # Example of using Google Drive API to list filenames in user's Drive. drive = Google::Apis::DriveV3::DriveService.new files = drive.list_files(options: { authorization: credentials }) "<pre>#{JSON.pretty_generate(files.to_h)}</pre>" else # User didn't authorize read-only Drive activity permission. # Update UX and application accordingly end # Check if user authorized Calendar read permission. if credentials.scope.include?(Google::Apis::CalendarV3::AUTH_CALENDAR_READONLY) # User authorized Calendar read permission. # Calling the APIs, etc. else # User didn't authorize Calendar read permission. # Update UX and application accordingly end end # Receive the callback from Google's OAuth 2.0 server. get '/oauth2callback' do # Handle the result of the oauth callback. Defers the exchange of the code by # temporarily stashing the results in the user's session. target_url = Google::Auth::WebUserAuthorizer.handle_auth_callback_deferred(request) redirect target_url end
Node.js
To run this example:
- В API Console, add the URL of the local machine to the list of redirect URLs. For example, add
http://localhost
. - Make sure you have maintenance LTS, active LTS, or current release of Node.js installed.
- Create a new directory and change to it. For example:
mkdir ~/nodejs-oauth2-example cd ~/nodejs-oauth2-example
- Install the Google API Client Library for Node.js using npm :
npm install googleapis
- Create the files
main.js
with the following content. - Run the example:
node .\main.js
main.js
const http = require('http'); const https = require('https'); const url = require('url'); const { google } = require('googleapis'); const crypto = require('crypto'); const express = require('express'); const session = require('express-session'); /** * To use OAuth2 authentication, we need access to a CLIENT_ID, CLIENT_SECRET, AND REDIRECT_URI. * To get these credentials for your application, visit * https://console.cloud.google.com/apis/credentials. */ const oauth2Client = new google.auth.OAuth2( YOUR_CLIENT_ID, YOUR_CLIENT_SECRET, YOUR_REDIRECT_URL ); // Access scopes for two non-Sign-In scopes: Read-only Drive activity and Google Calendar. const scopes = [ 'https://www.googleapis.com/auth/drive.metadata.readonly', 'https://www.googleapis.com/auth/calendar.readonly' ]; /* Global variable that stores user credential in this code example. * ACTION ITEM for developers: * Store user's refresh token in your data store if * incorporating this code into your real app. * For more information on handling refresh tokens, * see https://github.com/googleapis/google-api-nodejs-client#handling-refresh-tokens */ let userCredential = null; async function main() { const app = express(); app.use(session({ secret: 'your_secure_secret_key', // Replace with a strong secret resave: false, saveUninitialized: false, })); // Example on redirecting user to Google's OAuth 2.0 server. app.get('/', async (req, res) => { // Generate a secure random state value. const state = crypto.randomBytes(32).toString('hex'); // Store state in the session req.session.state = state; // Generate a url that asks permissions for the Drive activity and Google Calendar scope const authorizationUrl = oauth2Client.generateAuthUrl({ // 'online' (default) or 'offline' (gets refresh_token) access_type: 'offline', /** Pass in the scopes array defined above. * Alternatively, if only one scope is needed, you can pass a scope URL as a string */ scope: scopes, // Enable incremental authorization. Recommended as a best practice. include_granted_scopes: true, // Include the state parameter to reduce the risk of CSRF attacks. state: state }); res.redirect(authorizationUrl); }); // Receive the callback from Google's OAuth 2.0 server. app.get('/oauth2callback', async (req, res) => { // Handle the OAuth 2.0 server response let q = url.parse(req.url, true).query; if (q.error) { // An error response e.g. error=access_denied console.log('Error:' + q.error); } else if (q.state !== req.session.state) { //check state value console.log('State mismatch. Possible CSRF attack'); res.end('State mismatch. Possible CSRF attack'); } else { // Get access and refresh tokens (if access_type is offline) let { tokens } = await oauth2Client.getToken(q.code); oauth2Client.setCredentials(tokens); /** Save credential to the global variable in case access token was refreshed. * ACTION ITEM: In a production app, you likely want to save the refresh token * in a secure persistent database instead. */ userCredential = tokens; // User authorized the request. Now, check which scopes were granted. if (tokens.scope.includes('https://www.googleapis.com/auth/drive.metadata.readonly')) { // User authorized read-only Drive activity permission. // Example of using Google Drive API to list filenames in user's Drive. const drive = google.drive('v3'); drive.files.list({ auth: oauth2Client, pageSize: 10, fields: 'nextPageToken, files(id, name)', }, (err1, res1) => { if (err1) return console.log('The API returned an error: ' + err1); const files = res1.data.files; if (files.length) { console.log('Files:'); files.map((file) => { console.log(`${file.name} (${file.id})`); }); } else { console.log('No files found.'); } }); } else { // User didn't authorize read-only Drive activity permission. // Update UX and application accordingly } // Check if user authorized Calendar read permission. if (tokens.scope.includes('https://www.googleapis.com/auth/calendar.readonly')) { // User authorized Calendar read permission. // Calling the APIs, etc. } else { // User didn't authorize Calendar read permission. // Update UX and application accordingly } } }); // Example on revoking a token app.get('/revoke', async (req, res) => { // Build the string for the POST request let postData = "token=" + userCredential.access_token; // Options for POST request to Google's OAuth 2.0 server to revoke a token let postOptions = { host: 'oauth2.googleapis.com', port: '443', path: '/revoke', method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'Content-Length': Buffer.byteLength(postData) } }; // Set up the request const postReq = https.request(postOptions, function (res) { res.setEncoding('utf8'); res.on('data', d => { console.log('Response: ' + d); }); }); postReq.on('error', error => { console.log(error) }); // Post the request with data postReq.write(postData); postReq.end(); }); const server = http.createServer(app); server.listen(8080); } main().catch(console.error);
HTTP/REST
This Python example uses the Flask framework and the Requests library to demonstrate the OAuth 2.0 web flow. We recommend using the Google API Client Library for Python for this flow. (The example in the Python tab does use the client library.)
import json import flask import requests app = flask.Flask(__name__) # To get these credentials (CLIENT_ID CLIENT_SECRET) and for your application, visit # https://console.cloud.google.com/apis/credentials. CLIENT_ID = '123456789.apps.googleusercontent.com' CLIENT_SECRET = 'abc123' # Read from a file or environmental variable in a real app # Access scopes for two non-Sign-In scopes: Read-only Drive activity and Google Calendar. SCOPE = 'https://www.googleapis.com/auth/drive.metadata.readonly https://www.googleapis.com/auth/calendar.readonly' # Indicate where the API server will redirect the user after the user completes # the authorization flow. The redirect URI is required. The value must exactly # match one of the authorized redirect URIs for the OAuth 2.0 client, which you # configured in the API Console. If this value doesn't match an authorized URI, # you will get a 'redirect_uri_mismatch' error. REDIRECT_URI = 'http://example.com/oauth2callback' @app.route('/') def index(): if 'credentials' not in flask.session: return flask.redirect(flask.url_for('oauth2callback')) credentials = json.loads(flask.session['credentials']) if credentials['expires_in'] <= 0: return flask.redirect(flask.url_for('oauth2callback')) else: # User authorized the request. Now, check which scopes were granted. if 'https://www.googleapis.com/auth/drive.metadata.readonly' in credentials['scope']: # User authorized read-only Drive activity permission. # Example of using Google Drive API to list filenames in user's Drive. headers = {'Authorization': 'Bearer {}'.format(credentials['access_token'])} req_uri = 'https://www.googleapis.com/drive/v2/files' r = requests.get(req_uri, headers=headers).text else: # User didn't authorize read-only Drive activity permission. # Update UX and application accordingly r = 'User did not authorize Drive permission.' # Check if user authorized Calendar read permission. if 'https://www.googleapis.com/auth/calendar.readonly' in credentials['scope']: # User authorized Calendar read permission. # Calling the APIs, etc. r += 'User authorized Calendar permission.' else: # User didn't authorize Calendar read permission. # Update UX and application accordingly r += 'User did not authorize Calendar permission.' return r @app.route('/oauth2callback') def oauth2callback(): if 'code' not in flask.request.args: state = str(uuid.uuid4()) flask.session['state'] = state # Generate a url that asks permissions for the Drive activity # and Google Calendar scope. Then, redirect user to the url. auth_uri = ('https://accounts.google.com/o/oauth2/v2/auth?response_type=code' '&client_id={}&redirect_uri={}&scope={}&state={}').format(CLIENT_ID, REDIRECT_URI, SCOPE, state) return flask.redirect(auth_uri) else: if 'state' not in flask.request.args or flask.request.args['state'] != flask.session['state']: return 'State mismatch. Possible CSRF attack.', 400 auth_code = flask.request.args.get('code') data = {'code': auth_code, 'client_id': CLIENT_ID, 'client_secret': CLIENT_SECRET, 'redirect_uri': REDIRECT_URI, 'grant_type': 'authorization_code'} # Exchange authorization code for access and refresh tokens (if access_type is offline) r = requests.post('https://oauth2.googleapis.com/token', data=data) flask.session['credentials'] = r.text return flask.redirect(flask.url_for('index')) if __name__ == '__main__': import uuid app.secret_key = str(uuid.uuid4()) app.debug = False app.run()
Redirect URI validation rules
Google applies the following validation rules to redirect URIs in order to help developers keep their applications secure. Your redirect URIs must adhere to these rules. See RFC 3986 section 3 for the definition of domain, host, path, query, scheme and userinfo, mentioned below.
Validation rules | |
---|---|
Схема | Redirect URIs must use the HTTPS scheme, not plain HTTP. Localhost URIs (including localhost IP address URIs) are exempt from this rule. |
Хозяин | Хосты не могут быть представлены в виде необработанных IP-адресов. IP-адреса локальных хостов не подпадают под это правило. |
Домен | “googleusercontent.com” .goo.gl ) unless the app owns the domain. Furthermore, if an app that owns a shortener domain chooses to redirect to that domain, that redirect URI must either contain “/google-callback/” in its path or end with “/google-callback” . |
Userinfo | Redirect URIs cannot contain the userinfo subcomponent. |
Путь | Redirect URIs cannot contain a path traversal (also called directory backtracking), which is represented by an |
Запрос | Redirect URIs cannot contain open redirects . |
Фрагмент | Redirect URIs cannot contain the fragment component. |
Персонажи | Redirect URIs cannot contain certain characters including:
|
Incremental authorization
In the OAuth 2.0 protocol, your app requests authorization to access resources, which are identified by scopes. It is considered a best user-experience practice to request authorization for resources at the time you need them. To enable that practice, Google's authorization server supports incremental authorization. This feature lets you request scopes as they are needed and, if the user grants permission for the new scope, returns an authorization code that may be exchanged for a token containing all scopes the user has granted the project.
For example, an app that lets people sample music tracks and create mixes might need very few resources at sign-in time, perhaps nothing more than the name of the person signing in. However, saving a completed mix would require access to their Google Drive. Most people would find it natural if they only were asked for access to their Google Drive at the time the app actually needed it.
In this case, at sign-in time the app might request the openid
and profile
scopes to perform basic sign-in, and then later request the https://www.googleapis.com/auth/drive.file
scope at the time of the first request to save a mix.
To implement incremental authorization, you complete the normal flow for requesting an access token but make sure that the authorization request includes previously granted scopes. This approach allows your app to avoid having to manage multiple access tokens.
The following rules apply to an access token obtained from an incremental authorization:
- The token can be used to access resources corresponding to any of the scopes rolled into the new, combined authorization.
- When you use the refresh token for the combined authorization to obtain an access token, the access token represents the combined authorization and can be used for any of the
scope
values included in the response. - The combined authorization includes all scopes that the user granted to the API project even if the grants were requested from different clients. For example, if a user granted access to one scope using an application's desktop client and then granted another scope to the same application via a mobile client, the combined authorization would include both scopes.
- If you revoke a token that represents a combined authorization, access to all of that authorization's scopes on behalf of the associated user are revoked simultaneously.
The language-specific code samples in Step 1: Set authorization parameters and the sample HTTP/REST redirect URL in Step 2: Redirect to Google's OAuth 2.0 server all use incremental authorization. The code samples below also show the code that you need to add to use incremental authorization.
PHP
$client->setIncludeGrantedScopes(true);
Питон
In Python, set the include_granted_scopes
keyword argument to true
to ensure that an authorization request includes previously granted scopes. It is very possible that include_granted_scopes
will not be the only keyword argument that you set, as shown in the example below.
authorization_url, state = flow.authorization_url( # Enable offline access so that you can refresh an access token without # re-prompting the user for permission. Recommended for web server apps. access_type='offline', # Enable incremental authorization. Recommended as a best practice. include_granted_scopes='true')
Руби
auth_client.update!( :additional_parameters => {"include_granted_scopes" => "true"} )
Node.js
const authorizationUrl = oauth2Client.generateAuthUrl({ // 'online' (default) or 'offline' (gets refresh_token) access_type: 'offline', /** Pass in the scopes array defined above. * Alternatively, if only one scope is needed, you can pass a scope URL as a string */ scope: scopes, // Enable incremental authorization. Recommended as a best practice. include_granted_scopes: true });
HTTP/REST
GET https://accounts.google.com/o/oauth2/v2/auth? client_id=your_client_id& response_type=code& state=state_parameter_passthrough_value& scope=https%3A//www.googleapis.com/auth/drive.metadata.readonly%20https%3A//www.googleapis.com/auth/calendar.readonly& redirect_uri=https%3A//oauth2.example.com/code& prompt=consent& include_granted_scopes=true
Refreshing an access token (offline access)
Access tokens periodically expire and become invalid credentials for a related API request. You can refresh an access token without prompting the user for permission (including when the user is not present) if you requested offline access to the scopes associated with the token.
- If you use a Google API Client Library, the client object refreshes the access token as needed as long as you configure that object for offline access.
- If you are not using a client library, you need to set the
access_type
HTTP query parameter tooffline
when redirecting the user to Google's OAuth 2.0 server . In that case, Google's authorization server returns a refresh token when you exchange an authorization code for an access token. Then, if the access token expires (or at any other time), you can use a refresh token to obtain a new access token.
Requesting offline access is a requirement for any application that needs to access a Google API when the user is not present. For example, an app that performs backup services or executes actions at predetermined times needs to be able to refresh its access token when the user is not present. The default style of access is called online
.
Server-side web applications, installed applications, and devices all obtain refresh tokens during the authorization process. Refresh tokens are not typically used in client-side (JavaScript) web applications.
PHP
If your application needs offline access to a Google API, set the API client's access type to offline
:
$client->setAccessType("offline");
After a user grants offline access to the requested scopes, you can continue to use the API client to access Google APIs on the user's behalf when the user is offline. The client object will refresh the access token as needed.
Питон
In Python, set the access_type
keyword argument to offline
to ensure that you will be able to refresh the access token without having to re-prompt the user for permission. It is very possible that access_type
will not be the only keyword argument that you set, as shown in the example below.
authorization_url, state = flow.authorization_url( # Enable offline access so that you can refresh an access token without # re-prompting the user for permission. Recommended for web server apps. access_type='offline', # Enable incremental authorization. Recommended as a best practice. include_granted_scopes='true')
After a user grants offline access to the requested scopes, you can continue to use the API client to access Google APIs on the user's behalf when the user is offline. The client object will refresh the access token as needed.
Руби
If your application needs offline access to a Google API, set the API client's access type to offline
:
auth_client.update!( :additional_parameters => {"access_type" => "offline"} )
After a user grants offline access to the requested scopes, you can continue to use the API client to access Google APIs on the user's behalf when the user is offline. The client object will refresh the access token as needed.
Node.js
If your application needs offline access to a Google API, set the API client's access type to offline
:
const authorizationUrl = oauth2Client.generateAuthUrl({ // 'online' (default) or 'offline' (gets refresh_token) access_type: 'offline', /** Pass in the scopes array defined above. * Alternatively, if only one scope is needed, you can pass a scope URL as a string */ scope: scopes, // Enable incremental authorization. Recommended as a best practice. include_granted_scopes: true });
After a user grants offline access to the requested scopes, you can continue to use the API client to access Google APIs on the user's behalf when the user is offline. The client object will refresh the access token as needed.
Access tokens expire. This library will automatically use a refresh token to obtain a new access token if it is about to expire. An easy way to make sure you always store the most recent tokens is to use the tokens event:
oauth2Client.on('tokens', (tokens) => { if (tokens.refresh_token) { // store the refresh_token in your secure persistent database console.log(tokens.refresh_token); } console.log(tokens.access_token); });
This tokens event only occurs in the first authorization, and you need to have set your access_type
to offline
when calling the generateAuthUrl
method to receive the refresh token. If you have already given your app the requisiste permissions without setting the appropriate constraints for receiving a refresh token, you will need to re-authorize the application to receive a fresh refresh token.
To set the refresh_token
at a later time, you can use the setCredentials
method:
oauth2Client.setCredentials({ refresh_token: `STORED_REFRESH_TOKEN` });
Once the client has a refresh token, access tokens will be acquired and refreshed automatically in the next call to the API.
HTTP/REST
To refresh an access token, your application sends an HTTPS POST
request to Google's authorization server ( https://oauth2.googleapis.com/token
) that includes the following parameters:
Поля | |
---|---|
client_id | The client ID obtained from the API Console. |
client_secret | The client secret obtained from the API Console. |
grant_type | As defined in the OAuth 2.0 specification , this field's value must be set to refresh_token . |
refresh_token | The refresh token returned from the authorization code exchange. |
The following snippet shows a sample request:
POST /token HTTP/1.1 Host: oauth2.googleapis.com Content-Type: application/x-www-form-urlencoded client_id=your_client_id& client_secret=your_client_secret& refresh_token=refresh_token& grant_type=refresh_token
As long as the user has not revoked the access granted to the application, the token server returns a JSON object that contains a new access token. The following snippet shows a sample response:
{ "access_token": "1/fFAGRNJru1FTz70BzhT3Zg", "expires_in": 3920, "scope": "https://www.googleapis.com/auth/drive.metadata.readonly https://www.googleapis.com/auth/calendar.readonly", "token_type": "Bearer" }
Note that there are limits on the number of refresh tokens that will be issued; one limit per client/user combination, and another per user across all clients. You should save refresh tokens in long-term storage and continue to use them as long as they remain valid. If your application requests too many refresh tokens, it may run into these limits, in which case older refresh tokens will stop working.
Token revocation
In some cases a user may wish to revoke access given to an application. A user can revoke access by visiting Account Settings . See the Remove site or app access section of the Third-party sites & apps with access to your account support document for more information.
It is also possible for an application to programmatically revoke the access given to it. Programmatic revocation is important in instances where a user unsubscribes, removes an application, or the API resources required by an app have significantly changed. In other words, part of the removal process can include an API request to ensure the permissions previously granted to the application are removed.
PHP
To programmatically revoke a token, call revokeToken()
:
$client->revokeToken();
Питон
To programmatically revoke a token, make a request to https://oauth2.googleapis.com/revoke
that includes the token as a parameter and sets the Content-Type
header:
requests.post('https://oauth2.googleapis.com/revoke', params={'token': credentials.token}, headers = {'content-type': 'application/x-www-form-urlencoded'})
Руби
To programmatically revoke a token, make an HTTP request to the oauth2.revoke
endpoint:
uri = URI('https://oauth2.googleapis.com/revoke') response = Net::HTTP.post_form(uri, 'token' => auth_client.access_token)
The token can be an access token or a refresh token. If the token is an access token and it has a corresponding refresh token, the refresh token will also be revoked.
If the revocation is successfully processed, then the status code of the response is 200
. For error conditions, a status code 400
is returned along with an error code.
Node.js
To programmatically revoke a token, make an HTTPS POST request to /revoke
endpoint:
const https = require('https'); // Build the string for the POST request let postData = "token=" + userCredential.access_token; // Options for POST request to Google's OAuth 2.0 server to revoke a token let postOptions = { host: 'oauth2.googleapis.com', port: '443', path: '/revoke', method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'Content-Length': Buffer.byteLength(postData) } }; // Set up the request const postReq = https.request(postOptions, function (res) { res.setEncoding('utf8'); res.on('data', d => { console.log('Response: ' + d); }); }); postReq.on('error', error => { console.log(error) }); // Post the request with data postReq.write(postData); postReq.end();
The token parameter can be an access token or a refresh token. If the token is an access token and it has a corresponding refresh token, the refresh token will also be revoked.
If the revocation is successfully processed, then the status code of the response is 200
. For error conditions, a status code 400
is returned along with an error code.
HTTP/REST
To programmatically revoke a token, your application makes a request to https://oauth2.googleapis.com/revoke
and includes the token as a parameter:
curl -d -X -POST --header "Content-type:application/x-www-form-urlencoded" \ https://oauth2.googleapis.com/revoke?token={token}
The token can be an access token or a refresh token. If the token is an access token and it has a corresponding refresh token, the refresh token will also be revoked.
If the revocation is successfully processed, then the HTTP status code of the response is 200
. For error conditions, an HTTP status code 400
is returned along with an error code.
Time-based access
Time-based access allows a user to grant your app access to their data for a limited duration to complete an action. Time-based access is available in select Google products during the consent flow, giving users the option to grant access for a limited period of time. An example is the Data Portability API which enables a one-time transfer of data.
When a user grants your application time-based access, the refresh token will expire after the specified duration. Note that refresh tokens may be invalidated earlier under specific circumstances; see these cases for details. The refresh_token_expires_in
field returned in the authorization code exchange response represents the time remaining until the refresh token expires in such cases.
Implementing Cross-Account Protection
Дополнительным шагом для защиты аккаунтов пользователей является реализация Cross-Account Protection с помощью сервиса Cross-Account Protection от Google. Этот сервис позволяет подписаться на уведомления о событиях безопасности, которые предоставляют вашему приложению информацию о важных изменениях в аккаунте пользователя. Затем вы можете использовать эту информацию для принятия мер в зависимости от того, как вы решите реагировать на события.
Вот некоторые примеры типов событий, отправляемых в ваше приложение службой Cross-Account Protection от Google:
-
https://schemas.openid.net/secevent/risc/event-type/sessions-revoked
-
https://schemas.openid.net/secevent/oauth/event-type/token-revoked
-
https://schemas.openid.net/secevent/risc/event-type/account-disabled
Дополнительную информацию о реализации защиты перекрестных учетных записей и полный список доступных событий см. на странице Защита учетных записей пользователей с помощью защиты перекрестных учетных записей.