В этом документе объясняется, как приложения веб-сервера используют клиентские библиотеки API Google или конечные точки Google OAuth 2.0 для реализации авторизации OAuth 2.0 для доступа к API Google.
OAuth 2.0 позволяет пользователям обмениваться определенными данными с приложением, сохраняя при этом свои имена пользователей, пароли и другую информацию в тайне. Например, приложение может использовать OAuth 2.0 для получения разрешения от пользователей на хранение файлов на их Google Дисках.
Этот поток OAuth 2.0 предназначен специально для авторизации пользователей. Он предназначен для приложений, которые могут хранить конфиденциальную информацию и сохранять состояние. Надлежащим образом авторизованное приложение веб-сервера может получить доступ к API, когда пользователь взаимодействует с приложением или после того, как пользователь покинул приложение.
Приложения веб-сервера часто также используют учетные записи служб для авторизации запросов API, особенно при вызове облачных API для доступа к данным проекта, а не к данным пользователя. Приложения веб-сервера могут использовать учетные записи служб в сочетании с авторизацией пользователя.
Клиентские библиотеки
В примерах для конкретных языков на этой странице используются клиентские библиотеки API Google для реализации авторизации 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.
- В 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, должно иметь учетные данные авторизации, которые идентифицируют приложение на сервере Google OAuth 2.0. Следующие шаги объясняют, как создать учетные данные для вашего проекта. Затем ваши приложения могут использовать учетные данные для доступа к API, которые вы включили для этого проекта.
- Go to the Credentials page.
- Щелкните Создать учетные данные > Идентификатор клиента OAuth .
- Выберите тип веб-приложения .
- Заполните форму и нажмите Создать . Приложения, использующие такие языки и платформы, как PHP, Java, Python, Ruby и .NET, должны указывать авторизованные URI перенаправления . URI перенаправления — это конечные точки, на которые сервер OAuth 2.0 может отправлять ответы. Эти конечные точки должны соответствовать правилам проверки Google .
Для тестирования вы можете указать URI, которые ссылаются на локальный компьютер, например
http://localhost:8080
. Имея это в виду, обратите внимание, что все примеры в этом документе используютhttp://localhost:8080
в качестве URI перенаправления.Мы рекомендуем спроектировать конечные точки проверки подлинности вашего приложения таким образом, чтобы ваше приложение не предоставляло коды авторизации другим ресурсам на странице.
После создания учетных данных загрузите файл client_secret.json из API Console. Надежно сохраните файл в месте, к которому может получить доступ только ваше приложение.
Определение областей доступа
Области позволяют вашему приложению запрашивать доступ только к тем ресурсам, которые ему необходимы, а также позволяют пользователям контролировать объем доступа, который они предоставляют вашему приложению. Таким образом, может существовать обратная зависимость между количеством запрошенных областей действия и вероятностью получения согласия пользователя.
Прежде чем приступить к реализации авторизации OAuth 2.0, мы рекомендуем определить области, для доступа к которым вашему приложению потребуется разрешение.
Мы также рекомендуем, чтобы ваше приложение запрашивало доступ к областям авторизации через добавочный процесс авторизации , в котором ваше приложение запрашивает доступ к пользовательским данным в контексте. Эта передовая практика помогает пользователям легче понять, почему вашему приложению нужен доступ, который оно запрашивает.
Документ OAuth 2.0 API Scopes содержит полный список областей, которые вы можете использовать для доступа к Google API.
Требования к языку
Для запуска любого из примеров кода в этом документе вам потребуется учетная запись Google, доступ в Интернет и веб-браузер. Если вы используете одну из клиентских библиотек API, ознакомьтесь также с требованиями к конкретному языку ниже.
PHP
Для запуска примеров кода PHP в этом документе вам потребуется:
- PHP 5.6 или выше с установленным интерфейсом командной строки (CLI) и расширением JSON.
- Инструмент управления зависимостями Composer .
Клиентская библиотека API Google для PHP:
composer require google/apiclient:^2.10
питон
Для запуска примеров кода Python в этом документе вам потребуется:
- Python 2.6 или выше
- Инструмент управления пакетами pip .
- Клиентская библиотека API Google для Python:
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
Рубин
Для запуска примеров кода Ruby в этом документе вам потребуется:
- Руби 2.2.2 или выше
Клиентская библиотека API Google для Ruby:
gem install google-api-client
Фреймворк веб-приложений Sinatra Ruby.
gem install sinatra
Node.js
Для запуска примеров кода Node.js в этом документе вам потребуется:
- Техническая LTS, активная LTS или текущая версия Node.js.
Клиент Google API Node.js:
npm install googleapis
HTTP/ОТДЫХ
Вам не нужно устанавливать какие-либо библиотеки, чтобы иметь возможность напрямую вызывать конечные точки OAuth 2.0.
Получение токенов доступа OAuth 2.0
Следующие шаги показывают, как ваше приложение взаимодействует с сервером Google OAuth 2.0, чтобы получить согласие пользователя на выполнение запроса 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 Диску:
$client = new Google\Client(); $client->setAuthConfig('client_secret.json'); $client->addScope(Google\Service\Drive::DRIVE_METADATA_READONLY); $client->setRedirectUri('http://' . $_SERVER['HTTP_HOST'] . '/oauth2callback.php'); // 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'); // Using "consent" ensures that your application always receives a refresh token. // If you are not using offline access, you can omit this. $client->setApprovalPrompt('consent'); $client->setIncludeGrantedScopes(true); // incremental auth
В запросе указывается следующая информация:
Параметры | |||||||
---|---|---|---|---|---|---|---|
client_id | Необходимый Идентификатор клиента для вашего приложения. Вы можете найти это значение в API ConsoleCredentials page. В PHP вызовите функцию $client = new Google\Client(); $client->setAuthConfig('client_secret.json'); | ||||||
redirect_uri | Необходимый Определяет, куда сервер API перенаправляет пользователя после того, как пользователь завершит процесс авторизации. Значение должно точно совпадать с одним из авторизованных URI перенаправления для клиента OAuth 2.0, который вы настроили в API ConsoleCredentials pageвашего клиента. Если это значение не соответствует авторизованному URI перенаправления для предоставленного Обратите внимание, что схема Чтобы установить это значение в PHP, вызовите функцию $client->setRedirectUri('https://oauth2.example.com/code'); | ||||||
scope | Необходимый Разделенный пробелами список областей, определяющих ресурсы, к которым ваше приложение может получить доступ от имени пользователя. Эти значения сообщают экран согласия, который Google показывает пользователю. Области позволяют вашему приложению запрашивать доступ только к тем ресурсам, которые ему необходимы, а также позволяют пользователям контролировать объем доступа, который они предоставляют вашему приложению. Таким образом, существует обратная зависимость между количеством запрошенных областей действия и вероятностью получения согласия пользователя. Чтобы установить это значение в PHP, вызовите функцию $client->addScope(Google\Service\Drive::DRIVE_METADATA_READONLY); Мы рекомендуем, чтобы ваше приложение запрашивало доступ к областям авторизации в контексте, когда это возможно. Запрашивая доступ к пользовательским данным в контексте с помощью инкрементной авторизации , вы помогаете пользователям легче понять, почему вашему приложению нужен запрашиваемый доступ. | ||||||
access_type | рекомендуемые Указывает, может ли ваше приложение обновлять маркеры доступа, когда пользователь отсутствует в браузере. Допустимые значения параметра: Установите значение Чтобы установить это значение в PHP, вызовите функцию $client->setAccessType('offline'); | ||||||
state | рекомендуемые Задает любое строковое значение, которое ваше приложение использует для поддержания состояния между вашим запросом авторизации и ответом сервера авторизации. Сервер возвращает точное значение, которое вы отправляете в виде пары Вы можете использовать этот параметр для нескольких целей, таких как направление пользователя к правильному ресурсу в вашем приложении, отправка одноразовых номеров и предотвращение подделки межсайтовых запросов. Поскольку ваш Чтобы установить это значение в PHP, вызовите функцию $client->setState($sample_passthrough_value); | ||||||
include_granted_scopes | Необязательный Позволяет приложениям использовать добавочную авторизацию для запроса доступа к дополнительным областям в контексте. Если вы установите для этого параметра значение Чтобы установить это значение в PHP, вызовите функцию $client->setIncludeGrantedScopes(true); | ||||||
login_hint | Необязательный Если ваше приложение знает, какой пользователь пытается пройти аутентификацию, оно может использовать этот параметр, чтобы предоставить подсказку серверу аутентификации Google. Сервер использует подсказку, чтобы упростить процесс входа в систему, предварительно заполнив поле электронной почты в форме входа или выбрав соответствующий сеанс с несколькими входами. Задайте в качестве значения параметра адрес электронной почты или Чтобы установить это значение в PHP, вызовите функцию $client->setLoginHint('None'); | ||||||
prompt | Необязательный Разделенный пробелами и чувствительный к регистру список подсказок для представления пользователя. Если вы не укажете этот параметр, пользователю будет предложено только в первый раз, когда ваш проект запрашивает доступ. Дополнительные сведения см. в разделе Запрос повторного согласия . Чтобы установить это значение в PHP, вызовите функцию $client->setApprovalPrompt('consent'); Возможные значения:
|
питон
В следующем фрагменте кода используется модуль 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 # Use the client_secret.json file to identify the application requesting # authorization. The client ID (from that file) and access scopes are required. flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file( 'client_secret.json', scopes=['https://www.googleapis.com/auth/drive.metadata.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. 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( # 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')
В запросе указывается следующая информация:
Параметры | |||||||
---|---|---|---|---|---|---|---|
client_id | Необходимый Идентификатор клиента для вашего приложения. Вы можете найти это значение в API ConsoleCredentials page. В Python вызовите метод flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file( 'client_secret.json', scopes=['https://www.googleapis.com/auth/drive.metadata.readonly']) | ||||||
redirect_uri | Необходимый Определяет, куда сервер API перенаправляет пользователя после того, как пользователь завершит процесс авторизации. Значение должно точно совпадать с одним из авторизованных URI перенаправления для клиента OAuth 2.0, который вы настроили в API Consoleвашего клиента Credentials page. Если это значение не соответствует авторизованному URI перенаправления для предоставленного Обратите внимание, что схема Чтобы установить это значение в Python, установите свойство flow.redirect_uri = 'https://oauth2.example.com/code' | ||||||
scope | Необходимый Список областей, определяющих ресурсы, к которым ваше приложение может получить доступ от имени пользователя. Эти значения сообщают экран согласия, который Google показывает пользователю. Области позволяют вашему приложению запрашивать доступ только к тем ресурсам, которые ему необходимы, а также позволяют пользователям контролировать объем доступа, который они предоставляют вашему приложению. Таким образом, существует обратная зависимость между количеством запрошенных областей действия и вероятностью получения согласия пользователя. В Python используйте тот же метод, который вы использовали для установки flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file( 'client_secret.json', scopes=['https://www.googleapis.com/auth/drive.metadata.readonly']) Мы рекомендуем, чтобы ваше приложение запрашивало доступ к областям авторизации в контексте, когда это возможно. Запрашивая доступ к пользовательским данным в контексте с помощью инкрементной авторизации , вы помогаете пользователям легче понять, почему вашему приложению нужен запрашиваемый доступ. | ||||||
access_type | рекомендуемые Указывает, может ли ваше приложение обновлять маркеры доступа, когда пользователь отсутствует в браузере. Допустимые значения параметра: Установите значение В Python установите параметр authorization_url, state = flow.authorization_url( access_type='offline', include_granted_scopes='true') | ||||||
state | рекомендуемые Задает любое строковое значение, которое ваше приложение использует для поддержания состояния между вашим запросом авторизации и ответом сервера авторизации. Сервер возвращает точное значение, которое вы отправляете в виде пары Вы можете использовать этот параметр для нескольких целей, таких как направление пользователя к правильному ресурсу в вашем приложении, отправка одноразовых номеров и предотвращение подделки межсайтовых запросов. Поскольку ваш В Python установите параметр authorization_url, state = flow.authorization_url( access_type='offline', state=sample_passthrough_value, include_granted_scopes='true') | ||||||
include_granted_scopes | Необязательный Позволяет приложениям использовать добавочную авторизацию для запроса доступа к дополнительным областям в контексте. Если вы установите для этого параметра значение В Python установите параметр authorization_url, state = flow.authorization_url( access_type='offline', include_granted_scopes='true') | ||||||
login_hint | Необязательный Если ваше приложение знает, какой пользователь пытается пройти аутентификацию, оно может использовать этот параметр, чтобы предоставить подсказку серверу аутентификации Google. Сервер использует подсказку, чтобы упростить процесс входа в систему, предварительно заполнив поле электронной почты в форме входа или выбрав соответствующий сеанс с несколькими входами. Задайте в качестве значения параметра адрес электронной почты или В Python задайте параметр authorization_url, state = flow.authorization_url( access_type='offline', login_hint='None', include_granted_scopes='true') | ||||||
prompt | Необязательный Разделенный пробелами и чувствительный к регистру список подсказок для представления пользователя. Если вы не укажете этот параметр, пользователю будет предложено только в первый раз, когда ваш проект запрашивает доступ. Дополнительные сведения см. в разделе Запрос повторного согласия . В Python задайте параметр authorization_url, state = flow.authorization_url( access_type='offline', prompt='consent', include_granted_scopes='true') Возможные значения:
|
Рубин
Используйте созданный вами файл client_secrets.json для настройки объекта клиента в приложении. При настройке клиентского объекта вы указываете области, к которым должно получить доступ ваше приложение, а также URL-адрес конечной точки аутентификации вашего приложения, которая будет обрабатывать ответ от сервера OAuth 2.0.
Например, этот код запрашивает автономный доступ только для чтения к пользовательскому Google Диску:
require 'google/apis/drive_v2' require 'google/api_client/client_secrets' client_secrets = Google::APIClient::ClientSecrets.load auth_client = client_secrets.to_authorization auth_client.update!( :scope => 'https://www.googleapis.com/auth/drive.metadata.readonly', :redirect_uri => 'http://www.example.com/oauth2callback', :additional_parameters => { "access_type" => "offline", # offline access "include_granted_scopes" => "true" # incremental auth } )
Ваше приложение использует клиентский объект для выполнения операций OAuth 2.0, таких как создание URL-адресов запроса авторизации и применение маркеров доступа к HTTP-запросам.
Node.js
Фрагмент кода ниже создает объект google.auth.OAuth2
, который определяет параметры в запросе авторизации.
Этот объект использует информацию из вашего файла client_secret.json для идентификации вашего приложения. Чтобы запросить у пользователя разрешение на получение токена доступа, вы перенаправляете его на страницу согласия. Чтобы создать URL-адрес страницы согласия:
const {google} = require('googleapis'); /** * 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 read-only Drive activity. const scopes = [ 'https://www.googleapis.com/auth/drive.metadata.readonly' ]; // Generate a url that asks permissions for the Drive activity 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 });
Важное примечание . refresh_token
возвращается только при первой авторизации. Подробнее здесь .
HTTP/ОТДЫХ
Конечная точка Google OAuth 2.0 находится по адресу https://accounts.google.com/o/oauth2/v2/auth
. Эта конечная точка доступна только через HTTPS. Обычные HTTP-соединения отклоняются.
Сервер авторизации Google поддерживает следующие параметры строки запроса для приложений веб-сервера:
Параметры | |||||||
---|---|---|---|---|---|---|---|
client_id | Необходимый Идентификатор клиента для вашего приложения. Вы можете найти это значение в API ConsoleCredentials page. | ||||||
redirect_uri | Необходимый Определяет, куда сервер API перенаправляет пользователя после того, как пользователь завершит процесс авторизации. Значение должно точно совпадать с одним из авторизованных URI перенаправления для клиента OAuth 2.0, который вы настроили в API Consoleвашего клиента Credentials page. Если это значение не соответствует авторизованному URI перенаправления для предоставленного Обратите внимание, что схема | ||||||
response_type | Необходимый Определяет, возвращает ли конечная точка Google OAuth 2.0 код авторизации. Установите значение параметра для | ||||||
scope | Необходимый Разделенный пробелами список областей, определяющих ресурсы, к которым ваше приложение может получить доступ от имени пользователя. Эти значения сообщают экран согласия, который Google показывает пользователю. Области позволяют вашему приложению запрашивать доступ только к тем ресурсам, которые ему необходимы, а также позволяют пользователям контролировать объем доступа, который они предоставляют вашему приложению. Таким образом, существует обратная зависимость между количеством запрошенных областей действия и вероятностью получения согласия пользователя. Мы рекомендуем, чтобы ваше приложение запрашивало доступ к областям авторизации в контексте, когда это возможно. Запрашивая доступ к пользовательским данным в контексте с помощью инкрементной авторизации , вы помогаете пользователям легче понять, почему вашему приложению нужен запрашиваемый доступ. | ||||||
access_type | рекомендуемые Указывает, может ли ваше приложение обновлять маркеры доступа, когда пользователь отсутствует в браузере. Допустимые значения параметра: Установите значение | ||||||
state | рекомендуемые Задает любое строковое значение, которое ваше приложение использует для поддержания состояния между вашим запросом авторизации и ответом сервера авторизации. Сервер возвращает точное значение, которое вы отправляете в виде пары Вы можете использовать этот параметр для нескольких целей, таких как направление пользователя к правильному ресурсу в вашем приложении, отправка одноразовых номеров и предотвращение подделки межсайтовых запросов. Поскольку ваш | ||||||
include_granted_scopes | Необязательный Позволяет приложениям использовать добавочную авторизацию для запроса доступа к дополнительным областям в контексте. Если вы установите для этого параметра значение | ||||||
login_hint | Необязательный Если ваше приложение знает, какой пользователь пытается пройти аутентификацию, оно может использовать этот параметр, чтобы предоставить подсказку серверу аутентификации Google. Сервер использует подсказку, чтобы упростить процесс входа в систему, предварительно заполнив поле электронной почты в форме входа или выбрав соответствующий сеанс с несколькими входами. Задайте в качестве значения параметра адрес электронной почты или | ||||||
prompt | Необязательный Разделенный пробелами и чувствительный к регистру список подсказок для представления пользователя. Если вы не укажете этот параметр, пользователю будет предложено только в первый раз, когда ваш проект запрашивает доступ. Дополнительные сведения см. в разделе Запрос повторного согласия . Возможные значения:
|
Шаг 2. Перенаправление на сервер Google OAuth 2.0
Перенаправьте пользователя на сервер Google OAuth 2.0, чтобы инициировать процесс аутентификации и авторизации. Как правило, это происходит, когда вашему приложению сначала требуется доступ к данным пользователя. В случае добавочной авторизации этот шаг также происходит, когда вашему приложению сначала требуется доступ к дополнительным ресурсам, на доступ к которым у него еще нет разрешения.
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 = auth_client.authorization_uri.to_s
- Перенаправить пользователя на
auth_uri
.
Node.js
- Используйте сгенерированный URL-
authorizationUrl
из методаgenerateAuthUrl
шага 1 , чтобы запросить доступ с сервера Google OAuth 2.0. - Перенаправить пользователя на
authorizationUrl
.res.writeHead(301, { "Location": authorizationUrl });
HTTP/REST
Sample redirect to Google's authorization server
An example URL is shown below, with line breaks and spaces for readability.
https://accounts.google.com/o/oauth2/v2/auth? scope=https%3A//www.googleapis.com/auth/drive.metadata.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 отображает окно согласия, в котором отображается имя вашего приложения и службы API Google, для доступа к которым запрашивается разрешение с учетными данными пользователя, а также сводка областей доступа, которые должны быть предоставлены. Затем пользователь может дать согласие на предоставление доступа к одной или нескольким областям, запрошенным вашим приложением, или отклонить запрос.
Вашему приложению не нужно ничего делать на этом этапе, так как оно ожидает ответа от сервера Google OAuth 2.0, указывающего, был ли предоставлен какой-либо доступ. Этот ответ объясняется в следующем шаге.
Ошибки
Запросы к конечной точке авторизации OAuth 2.0 Google могут отображать сообщения об ошибках вместо ожидаемых потоков аутентификации и авторизации. Распространенные коды ошибок и предлагаемые решения перечислены ниже.
admin_policy_enforced
Аккаунт Google не может авторизовать одну или несколько запрошенных областей из-за правил администратора Google Workspace. Дополнительную информацию о том, как администратор может ограничить доступ ко всем областям или конфиденциальным и ограниченным областям, см. в справочной статье для администраторов Google Workspace Контролируйте, какие сторонние и внутренние приложения получают доступ к данным Google Workspace, пока доступ явно не предоставлен вашему идентификатору клиента OAuth.
disallowed_useragent
Конечная точка авторизации отображается внутри встроенного пользовательского агента, запрещенного политиками Google OAuth 2.0 .
Андроид
Разработчики Android могут столкнуться с этим сообщением об ошибке при открытии запросов авторизации в android.webkit.WebView
. Вместо этого разработчикам следует использовать библиотеки Android, такие как Google Sign-In для Android или AppAuth OpenID Foundation для Android .
Веб-разработчики могут столкнуться с этой ошибкой, когда приложение Android открывает общую веб-ссылку во встроенном пользовательском агенте, а пользователь переходит к конечной точке авторизации Google OAuth 2.0 с вашего сайта. Разработчики должны разрешать открытие общих ссылок в обработчике ссылок по умолчанию операционной системы, который включает в себя как обработчики ссылок приложений Android , так и приложение браузера по умолчанию. Библиотека пользовательских вкладок Android также является поддерживаемым вариантом.
iOS
Разработчики iOS и macOS могут столкнуться с этой ошибкой при открытии запросов авторизации в WKWebView
. Вместо этого разработчикам следует использовать библиотеки iOS, такие как Google Sign-In для iOS или AppAuth OpenID Foundation для iOS .
Веб-разработчики могут столкнуться с этой ошибкой, когда приложение iOS или macOS открывает общую веб-ссылку во встроенном пользовательском агенте, и пользователь переходит к конечной точке авторизации OAuth 2.0 Google с вашего сайта. Разработчики должны разрешить открытие общих ссылок в обработчике ссылок по умолчанию операционной системы, который включает в себя как обработчики универсальных ссылок , так и приложение браузера по умолчанию. Библиотека SFSafariViewController
также является поддерживаемым вариантом.
org_internal
Идентификатор клиента OAuth в запросе является частью проекта, ограничивающего доступ к аккаунтам Google в определенной организации Google Cloud . Дополнительные сведения об этом параметре конфигурации см. в разделе «Тип пользователя» справочной статьи «Настройка экрана согласия OAuth».
invalid_client
Неверный секрет клиента OAuth. Просмотрите конфигурацию клиента OAuth , включая идентификатор клиента и секрет, используемые для этого запроса.
invalid_grant
При обновлении токена доступа или использовании добавочной авторизации срок действия токена мог быть истёк или он стал недействительным. Повторно аутентифицируйте пользователя и запросите согласие пользователя на получение новых токенов. Если вы продолжаете видеть эту ошибку, убедитесь, что ваше приложение настроено правильно и что вы используете правильные токены и параметры в своем запросе. В противном случае учетная запись пользователя могла быть удалена или отключена.
redirect_uri_mismatch
redirect_uri
переданный в запросе авторизации, не соответствует авторизованному URI перенаправления для идентификатора клиента OAuth. Просмотрите разрешенные URI перенаправления в Google API Console Credentials page.
Параметр redirect_uri
может относиться к внешнему потоку OAuth (OOB), который устарел и больше не поддерживается. Обратитесь к руководству по миграции , чтобы обновить интеграцию.
Шаг 4. Обработайте ответ сервера OAuth 2.0
The OAuth 2.0 server responds to your application's access request by using the URL specified in the request.
If the user approves the access request, then the response contains an authorization code. If the user does not approve the request, the response contains an error message. The authorization code or error message that is returned to the web server appears on the query string, as shown below:
An error response:
https://oauth2.example.com/auth?error=access_denied
An authorization code response:
https://oauth2.example.com/auth?code=4/P7q7W91a-oMsCeLvIaQm6bTrgtp7
Sample OAuth 2.0 server response
You can test this flow by clicking on the following sample URL, which requests read-only access to view metadata for files in your Google Drive:
https://accounts.google.com/o/oauth2/v2/auth? scope=https%3A//www.googleapis.com/auth/drive.metadata.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
After completing the OAuth 2.0 flow, you should be redirected to http://localhost/oauth2callback
, which will likely yield a 404 NOT FOUND
error unless your local machine serves a file at that address. The next step provides more detail about the information returned in the URI when the user is redirected back to your application.
Step 5: Exchange authorization code for refresh and access tokens
After the web server receives the authorization code, it can exchange the authorization code for an access token.
PHP
To exchange an authorization code for an access token, use the authenticate
method:
$client->authenticate($_GET['code']);
You can retrieve the access token with the getAccessToken
method:
$access_token = $client->getAccessToken();
питон
On your callback page, use the google-auth
library to verify the authorization server response. Then, use the flow.fetch_token
method to exchange the authorization code in that response for an access 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 the session. # ACTION ITEM for developers: # Store user's access and refresh tokens in your data store if # incorporating this code into your real app. credentials = flow.credentials flask.session['credentials'] = { 'token': credentials.token, 'refresh_token': credentials.refresh_token, 'token_uri': credentials.token_uri, 'client_id': credentials.client_id, 'client_secret': credentials.client_secret, 'scopes': credentials.scopes}
Рубин
To exchange an authorization code for an access token, use the fetch_access_token!
method:
auth_client.code = auth_code auth_client.fetch_access_token!
Node.js
To exchange an authorization code for an access token, use the getToken
method:
const url = require('url'); // Receive the callback from Google's OAuth 2.0 server. if (req.url.startsWith('/oauth2callback')) { // Handle the OAuth 2.0 server response let q = url.parse(req.url, true).query; // Get access and refresh tokens (if access_type is offline) let { tokens } = await oauth2Client.getToken(q.code); oauth2Client.setCredentials(tokens); }
HTTP/REST
To exchange an authorization code for an access token, call the https://oauth2.googleapis.com/token
endpoint and set the following parameters:
Поля | |
---|---|
client_id | The client ID obtained from the API ConsoleCredentials page. |
client_secret | The client secret obtained from the API ConsoleCredentials page. |
code | The authorization code returned from the initial request. |
grant_type | As defined in the OAuth 2.0 specification , this field's value must be set to authorization_code . |
redirect_uri | One of the redirect URIs listed for your project in the API ConsoleCredentials page for the given client_id . |
The following snippet shows a sample request:
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 responds to this request by returning a JSON object that contains a short-lived access token and a refresh token. Note that the refresh token is only returned if your application set the access_type
parameter to offline
in the initial request to Google's authorization server .
The response contains the following fields:
Поля | |
---|---|
access_token | The token that your application sends to authorize a Google API request. |
expires_in | The remaining lifetime of the access token in seconds. |
refresh_token | A token that you can use to obtain a new access token. Refresh tokens are valid until the user revokes access. Again, this field is only present in this response if you set the access_type parameter to offline in the initial request to Google's authorization server. |
scope | The scopes of access granted by the access_token expressed as a list of space-delimited, case-sensitive strings. |
token_type | The type of token returned. At this time, this field's value is always set to Bearer . |
The following snippet shows a sample response:
{ "access_token": "1/fFAGRNJru1FTz70BzhT3Zg", "expires_in": 3920, "token_type": "Bearer", "scope": "https://www.googleapis.com/auth/drive.metadata.readonly", "refresh_token": "1//xEoDL4iW3cxlI7yDbSRFYNG01kVKM2C-259HOF2aQbI" }
Ошибки
When exchanging the authorization code for an access token you may encounter the following error instead of the expected response. Common error codes and suggested resolutions are listed below.
invalid_grant
The supplied authorization code is invalid or in the wrong format. Request a new code by restarting the OAuth process to prompt the user for consent again.
Calling Google APIs
PHP
Use the access token to call Google APIs by completing the following steps:
- If you need to apply an access token to a new
Google\Client
object — for example, if you stored the access token in a user session — use thesetAccessToken
method:$client->setAccessToken($access_token);
- Build a service object for the API that you want to call. You build a service object by providing an authorized
Google\Client
object to the constructor for the API you want to call. For example, to call the Drive API:$drive = new Google\Service\Drive($client);
- Make requests to the API service using the interface provided by the service object . For example, to list the files in the authenticated user's Google Drive:
$files = $drive->files->listFiles(array())->getItems();
питон
After obtaining an access token, your application can use that token to authorize API requests on behalf of a given user account or service account. Use the user-specific authorization credentials to build a service object for the API that you want to call, and then use that object to make authorized API requests.
- Build a service object for the API that you want to call. You build a service object by calling the
googleapiclient.discovery
library'sbuild
method with the name and version of the API and the user credentials: For example, to call version 2 of the Drive API:from googleapiclient.discovery import build drive = build('drive', 'v2', credentials=credentials)
- Make requests to the API service using the interface provided by the service object . For example, to list the files in the authenticated user's Google Drive:
files = drive.files().list().execute()
Рубин
Use the auth_client
object to call Google APIs by completing the following steps:
- Build a service object for the API that you want to call. For example, to call version 2 of the Drive API:
drive = Google::Apis::DriveV2::DriveService.new
- Set the credentials on the service:
drive.authorization = auth_client
- Make requests to the API service using the interface provided by the service object . For example, to list the files in the authenticated user's Google Drive:
files = drive.list_files
Alternately, authorization can be provided on a per-method basis by supplying the options
parameter to a method:
files = drive.list_files(options: { authorization: auth_client })
Node.js
After obtaining an access token and setting it to the OAuth2
object, use the object to call Google APIs. Your application can use that token to authorize API requests on behalf of a given user account or service account. Build a service object for the API that you want to call.
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:
- In the 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.10
- Create the files
index.php
andoauth2callback.php
with the content below. - Run the example with a web server configured to serve PHP. If you use PHP 5.6 or newer, you can use 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_secrets.json'); $client->addScope(Google\Service\Drive::DRIVE_METADATA_READONLY); if (isset($_SESSION['access_token']) && $_SESSION['access_token']) { $client->setAccessToken($_SESSION['access_token']); $drive = new Google\Service\Drive($client); $files = $drive->files->listFiles(array())->getItems(); echo json_encode($files); } else { $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(); $client->setAuthConfigFile('client_secrets.json'); $client->setRedirectUri('http://' . $_SERVER['HTTP_HOST'] . '/oauth2callback.php'); $client->addScope(Google\Service\Drive::DRIVE_METADATA_READONLY); if (! isset($_GET['code'])) { $auth_url = $client->createAuthUrl(); header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL)); } else { $client->authenticate($_GET['code']); $_SESSION['access_token'] = $client->getAccessToken(); $redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/'; header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL)); }
питон
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 four links:
- Test an API request: This link points to a page that tries to execute a sample API request. 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 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" # This OAuth 2.0 access scope allows for full read/write access to the # authenticated user's account and requires requests to use an SSL connection. SCOPES = ['https://www.googleapis.com/auth/drive.metadata.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('/test') def test_api_request(): if 'credentials' not in flask.session: return flask.redirect('authorize') # Load credentials from the session. credentials = google.oauth2.credentials.Credentials( **flask.session['credentials']) 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. # ACTION ITEM: In a production app, you likely want to save these # credentials in a persistent database instead. flask.session['credentials'] = credentials_to_dict(credentials) return flask.jsonify(**files) @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 flask.session['credentials'] = credentials_to_dict(credentials) return flask.redirect(flask.url_for('test_api_request')) @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.') credentials = google.oauth2.credentials.Credentials( **flask.session['credentials']) 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: 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, 'token_uri': credentials.token_uri, 'client_id': credentials.client_id, 'client_secret': credentials.client_secret, 'scopes': credentials.scopes} def print_index_table(): return ('<table>' + '<tr><td><a href="/test">Test an API request</a></td>' + '<td>Submit an API request and see a formatted JSON response. ' + ' Go through the authorization flow if there are no stored ' + ' credentials for the user.</td></tr>' + '<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="/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="/test">test the ' + ' API request</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' # 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 'google/apis/drive_v2' require 'google/api_client/client_secrets' require 'json' require 'sinatra' enable :sessions set :session_secret, 'setme' get '/' do unless session.has_key?(:credentials) redirect to('/oauth2callback') end client_opts = JSON.parse(session[:credentials]) auth_client = Signet::OAuth2::Client.new(client_opts) drive = Google::Apis::DriveV2::DriveService.new files = drive.list_files(options: { authorization: auth_client }) "<pre>#{JSON.pretty_generate(files.to_h)}</pre>" end get '/oauth2callback' do client_secrets = Google::APIClient::ClientSecrets.load auth_client = client_secrets.to_authorization auth_client.update!( :scope => 'https://www.googleapis.com/auth/drive.metadata.readonly', :redirect_uri => url('/oauth2callback')) if request['code'] == nil auth_uri = auth_client.authorization_uri.to_s redirect to(auth_uri) else auth_client.code = request['code'] auth_client.fetch_access_token! auth_client.client_secret = nil session[:credentials] = auth_client.to_json redirect to('/') end end
Node.js
To run this example:
- In the 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 content below. - Run the example:
node .\main.js
main.js
const http = require('http'); const https = require('https'); const url = require('url'); const { google } = require('googleapis'); /** * 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 read-only Drive activity. const scopes = [ 'https://www.googleapis.com/auth/drive.metadata.readonly' ]; // Generate a url that asks permissions for the Drive activity 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 }); /* 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 server = http.createServer(async function (req, res) { // Example on redirecting user to Google's OAuth 2.0 server. if (req.url == '/') { res.writeHead(301, { "Location": authorizationUrl }); } // Receive the callback from Google's OAuth 2.0 server. if (req.url.startsWith('/oauth2callback')) { // 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 { // 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; // 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.'); } }); } } // Example on revoking a token if (req.url == '/revoke') { // 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(); } res.end(); }).listen(80); } 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__) CLIENT_ID = '123456789.apps.googleusercontent.com' CLIENT_SECRET = 'abc123' # Read from a file or environmental variable in a real app SCOPE = 'https://www.googleapis.com/auth/drive.metadata.readonly' 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: headers = {'Authorization': 'Bearer {}'.format(credentials['access_token'])} req_uri = 'https://www.googleapis.com/drive/v2/files' r = requests.get(req_uri, headers=headers) return r.text @app.route('/oauth2callback') def oauth2callback(): if 'code' not in flask.request.args: auth_uri = ('https://accounts.google.com/o/oauth2/v2/auth?response_type=code' '&client_id={}&redirect_uri={}&scope={}').format(CLIENT_ID, REDIRECT_URI, SCOPE) return flask.redirect(auth_uri) else: 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'} 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 | |
---|---|
Scheme | Redirect URIs must use the HTTPS scheme, not plain HTTP. Localhost URIs (including localhost IP address URIs) are exempt from this rule. |
Host | Hosts cannot be raw IP addresses. Localhost IP addresses are exempted from this rule. |
Domain | “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. |
Path | Redirect URIs cannot contain a path traversal (also called directory backtracking), which is represented by an |
Query | Redirect URIs cannot contain open redirects . |
Fragment | Redirect URIs cannot contain the fragment component. |
Characters | 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.file& 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", "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.
Revoking a token
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.