blob: da8509625f77053b309428344f5d14e661117638 [file] [log] [blame] [view]
Grant Timmerman5c11b0a2019-06-26 07:39:48 -07001# Using OAuth 2.0 for Server to Server Applications
2
3The Google APIs Client Library for Python supports using OAuth 2.0 for server-to-server interactions such as those between a web application and a Google service. For this scenario you need a service account, which is an account that belongs to your application instead of to an individual end user. Your application calls Google APIs on behalf of the service account, so users aren't directly involved. This scenario is sometimes called "two-legged OAuth," or "2LO." (The related term "three-legged OAuth" refers to scenarios in which your application calls Google APIs on behalf of end users, and in which user consent is sometimes required.)
4
5Typically, an application uses a service account when the application uses Google APIs to work with its own data rather than a user's data. For example, an application that uses [Google Cloud Datastore](https://cloud.google.com/datastore/) for data persistence would use a service account to authenticate its calls to the Google Cloud Datastore API.
6
Bu Sun Kim8496ebe2019-08-12 18:04:35 -07007If you have a G Suite domainif you use [G Suite](https://gsuite.google.com/), for example—an administrator of the G Suite domain can authorize an application to access user data on behalf of users in the G Suite domain. For example, an application that uses the [Google Calendar API](https://developers.google.com/calendar/) to add events to the calendars of all users in a G Suite domain would use a service account to access the Google Calendar API on behalf of users. Authorizing a service account to access data on behalf of users in a domain is sometimes referred to as "delegating domain-wide authority" to a service account.
Grant Timmerman5c11b0a2019-06-26 07:39:48 -07008
9> **Note:** When you use [G Suite Marketplace](https://www.google.com/enterprise/marketplace/) to install an application for your domain, the required permissions are automatically granted to the application. You do not need to manually authorize the service accounts that the application uses.
10
Liron Newmanfb6fcc82020-04-21 18:53:01 +010011> **Note:** Although you can use service accounts in applications that run from a G Suite domain, service accounts are not members of your G Suite account and aren't subject to domain policies set by G Suite administrators. For example, a policy set in the G Suite Admin console to restrict the ability of G Suite end users to share documents outside of the domain would not apply to service accounts. Similarly, that policy would prevent users from sharing documents with service accounts, because service acounts are always outside of the domain. If you're using G Suite domain-wide delegation, this isn't relevant to you - you are accessing APIs while acting as a domain user, not as the service account itself.
Grant Timmerman5c11b0a2019-06-26 07:39:48 -070012
13This document describes how an application can complete the server-to-server OAuth 2.0 flow by using the Google APIs Client Library for Python.
14
15## Overview
16
Liron Newmanfb6fcc82020-04-21 18:53:01 +010017To support server-to-server interactions, first create a service account for your project in the API Console. If you want to access user data for users in your G Suite domain, then delegate domain-wide access to the service account.
Grant Timmerman5c11b0a2019-06-26 07:39:48 -070018
19Then, your application prepares to make authorized API calls by using the service account's credentials to request an access token from the OAuth 2.0 auth server.
20
21Finally, your application can use the access token to call Google APIs.
22
23## Creating a service account
24
25A service account's credentials include a generated email address that is unique, a client ID, and at least one public/private key pair.
26
27If your application runs on Google App Engine, a service account is set up automatically when you create your project.
28
29If your application runs on Google Compute Engine, a service account is also set up automatically when you create your project, but you must specify the scopes that your application needs access to when you create a Google Compute Engine instance. For more information, see [Preparing an instance to use service accounts](https://cloud.google.com/compute/docs/authentication#using).
30
31If your application doesn't run on Google App Engine or Google Compute Engine, you must obtain these credentials in the Google API Console. To generate service-account credentials, or to view the public credentials that you've already generated, do the following:
32
331. Open the [**Service accounts** page](https://console.developers.google.com/permissions/serviceaccounts). If prompted, select a project.
341. Click **Create service account**.
351. In the **Create service account** window, type a name for the service account, and select **Furnish a new private key**. If you want to [grant G Suite domain-wide authority](https://developers.google.com/identity/protocols/OAuth2ServiceAccount#delegatingauthority) to the service account, also select **Enable G Suite Domain-wide Delegation**. Then click **Create**.
36
37Your new public/private key pair is generated and downloaded to your machine; it serves as the only copy of this key. You are responsible for storing it securely.
38
39You can return to the [API Console](https://console.developers.google.com/) at any time to view the client ID, email address, and public key fingerprints, or to generate additional public/private key pairs. For more details about service account credentials in the API Console, see [Service accounts](https://developers.google.com/console/help/service-accounts) in the API Console help file.
40
41Take note of the service account's email address and store the service account's private key file in a location accessible to your application. Your application needs them to make authorized API calls.
42
43> **Note:** You must store and manage private keys securely in both development and production environments. Google does not keep a copy of your private keys, only your public keys.
44
45## Delegating domain-wide authority to the service account
46
Liron Newmanfb6fcc82020-04-21 18:53:01 +010047If your application runs in a G Suite domain and accesses user data, the service account that you created needs to be granted access to the user data that you want to access.
Grant Timmerman5c11b0a2019-06-26 07:39:48 -070048
Liron Newmanfb6fcc82020-04-21 18:53:01 +010049The following steps must be performed by an administrator of the G Suite domain:
Grant Timmerman5c11b0a2019-06-26 07:39:48 -070050
Liron Newmanfb6fcc82020-04-21 18:53:01 +0100511. Go to your G Suite domain’s [Admin console](https://admin.google.com/).
Grant Timmerman5c11b0a2019-06-26 07:39:48 -0700521. Select **Security** from the list of controls. If you don't see **Security** listed, select **More controls** from the gray bar at the bottom of the page, then select **Security** from the list of controls. If you can't see the controls, make sure you're signed in as an administrator for the domain.
531. Select **Advanced settings** from the list of options.
541. Select **Manage third party OAuth Client access** in the **Authentication** section.
551. In the **Client name** field enter the service account's **Client ID**.
Liron Newmanfb6fcc82020-04-21 18:53:01 +0100561. In the **One or More API Scopes** field enter the list of scopes that your application should be granted access to. For example, if your application needs domain-wide access to the Google Drive API and the Google Calendar API, enter: `https://www.googleapis.com/auth/drive, https://www.googleapis.com/auth/calendar`.
Grant Timmerman5c11b0a2019-06-26 07:39:48 -0700571. Click **Authorize**.
58
Liron Newmanfb6fcc82020-04-21 18:53:01 +010059Your application now has the authority to make API calls as users in your domain (to "impersonate" users). When you prepare to make authorized API calls, you specify the user to impersonate in the `subject` argument.
Grant Timmerman5c11b0a2019-06-26 07:39:48 -070060
61## Preparing to make an authorized API call
62
63After you obtain the client email address and private key from the API Console, complete the following steps:
64
651. Install the required libraries:
66
67 ```sh
68 pip install google-auth google-auth-httplib2 google-api-python-client
69 ```
70
711. Create a `Credentials` object from the service account's credentials and the scopes your application needs access to. For example:
72
73### Examples
74
75#### Google App Engine standard environment
76
Bu Sun Kim8496ebe2019-08-12 18:04:35 -070077```python
Grant Timmerman5c11b0a2019-06-26 07:39:48 -070078from google.auth import app_engine
79
80SCOPES = ['https://www.googleapis.com/auth/sqlservice.admin']
81
82credentials = app_engine.Credentials(scopes=SCOPES)
83```
84
Bu Sun Kim8496ebe2019-08-12 18:04:35 -070085> **Note:** You can only use App Engine credential objects in applications that are running in a Google App Engine standard environment. If you need to run your application in other environmentsfor example, to test your application locallyyou must detect this situation and use a different credential mechanism (see [https://google-auth.readthedocs.io/en/latest/user-guide.html#the-app-engine-standard-environment)).
Grant Timmerman5c11b0a2019-06-26 07:39:48 -070086
87#### Google Compute Engine
88
Bu Sun Kim8496ebe2019-08-12 18:04:35 -070089```python
Grant Timmerman5c11b0a2019-06-26 07:39:48 -070090from google.auth import compute_engine
91
92credentials = compute_engine.Credentials()
93```
94
95You must [configure your Compute Engine instance to allow access to the necessary scopes](https://cloud.google.com/compute/docs/access/create-enable-service-accounts-for-instances#changeserviceaccountandscopes).
96
Bu Sun Kim8496ebe2019-08-12 18:04:35 -070097> **Note:** You can only use Compute Engine credential objects in applications that are running on Google Compute Engine. If you need to run your application in other environmentsfor example, to test your application locallyyou must detect this situation and use a different credential mechanism (see [Other platforms](https://google-auth.readthedocs.io/en/latest/user-guide.html#compute-engine-container-engine-and-the-app-engine-flexible-environment)). You can use the [application default credentials](https://developers.google.com/accounts/docs/application-default-credentials) to simplify this process.
Grant Timmerman5c11b0a2019-06-26 07:39:48 -070098
99#### Other Platforms
100
Bu Sun Kim8496ebe2019-08-12 18:04:35 -0700101```python
Grant Timmerman5c11b0a2019-06-26 07:39:48 -0700102from google.oauth2 import service_account
103
104SCOPES = ['https://www.googleapis.com/auth/sqlservice.admin']
105SERVICE_ACCOUNT_FILE = '/path/to/service.json'
106
107credentials = service_account.Credentials.from_service_account_file(
108 SERVICE_ACCOUNT_FILE, scopes=SCOPES)
109```
110
111Use the `Credentials` object to call Google APIs in your application.
112
Liron Newmanfb6fcc82020-04-21 18:53:01 +0100113#### Using Domain-wide Delegation
114
115```python
116from google.oauth2 import service_account
117
118SCOPES = ['https://www.googleapis.com/auth/sqlservice.admin']
119SERVICE_ACCOUNT_FILE = '/path/to/service.json'
120
121credentials = service_account.Credentials.from_service_account_file(
122 SERVICE_ACCOUNT_FILE, scopes=SCOPES, subject='user@domain.com')
123```
124
125Use the `Credentials` object to call Google APIs in your application. The API requests would be authorized as `user@domain.com`, if you've authorized the service account accordingly in the G Suite Admin console.
126
127
Grant Timmerman5c11b0a2019-06-26 07:39:48 -0700128## Calling Google APIs
129
130To call a Google API using the `Credentials` object, complete the following steps:
131
1321. Build a service object for the API that you want to call. You build a a service object by calling the build function with the name and version of the API and the authorized Http object. For example, to call version 1beta3 of the [Cloud SQL Administration API](https://cloud.google.com/sql/docs/admin-api/):
133
Bu Sun Kim8496ebe2019-08-12 18:04:35 -0700134 ```python
Grant Timmerman5c11b0a2019-06-26 07:39:48 -0700135 import googleapiclient.discovery
136
137 sqladmin = googleapiclient.discovery.build('sqladmin', 'v1beta3', credentials=credentials)
138 ```
139
Bu Sun Kim8496ebe2019-08-12 18:04:35 -07001401. Make requests to the API service using the interface provided by the service object. For example, to list the instances of Cloud SQL databases in the example-123 project:
Grant Timmerman5c11b0a2019-06-26 07:39:48 -0700141
Bu Sun Kim8496ebe2019-08-12 18:04:35 -0700142 ```python
Grant Timmerman5c11b0a2019-06-26 07:39:48 -0700143 response = sqladmin.instances().list(project='example-123').execute()
144 ```
145
146## Complete example
147
148The following example prints a JSON-formatted list of Cloud SQL instances in a project.
149
Bu Sun Kim8496ebe2019-08-12 18:04:35 -0700150```python
Grant Timmerman5c11b0a2019-06-26 07:39:48 -0700151from google.oauth2 import service_account
152import googleapiclient.discovery
153
154SCOPES = ['https://www.googleapis.com/auth/sqlservice.admin']
155SERVICE_ACCOUNT_FILE = '/path/to/service.json'
156
157credentials = service_account.Credentials.from_service_account_file(
158 SERVICE_ACCOUNT_FILE, scopes=SCOPES)
159sqladmin = googleapiclient.discovery.build('sqladmin', 'v1beta3', credentials=credentials)
160response = sqladmin.instances().list(project='exemplary-example-123').execute()
161
162print(response)
Liron Newmanfb6fcc82020-04-21 18:53:01 +0100163```