• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Using OAuth 2.0 for Installed Applications
2
3The Google APIs Client Library for Python supports using OAuth 2.0 in applications that are installed on a device such as a computer, a cell phone, or a tablet. Installed apps are distributed to individual machines, and it is assumed that these apps cannot keep secrets. These apps might access a Google API while the user is present at the app, or when the app is running in the background.
4
5This document is for you if:
6
7- You are writing an installed app for a platform other than Android or iOS, and
8- Your installed app will run on devices that have a system browser and rich input capabilities, such as devices with full keyboards.
9
10If you are writing an app for Android or iOS, use [Google Sign-In](https://developers.google.com/identity) to authenticate your users. The Google Sign-In button manages the OAuth 2.0 flow both for authentication and for obtaining authorization to Google APIs. To add the Google Sign-In button, follow the steps for [Android](https://developers.google.com/identity/sign-in/android) or [iOS](https://developers.google.com/identity/sign-in/ios).
11
12If your app will run on devices that do not have access to a system browser, or devices with limited input capabilities (for example, if your app will run on game consoles, video cameras, or printers), then see [Using OAuth 2.0 for Devices](https://developers.google.com/accounts/docs/OAuth2ForDevices).
13
14## Overview
15
16To use OAuth 2.0 in a locally-installed application, first create application credentials for your project in the API Console.
17
18Then, when your application needs to access a user's data with a Google API, your application sends the user to Google's OAuth 2.0 server. The OAuth 2.0 server authenticates the user and obtains consent from the user for your application to access the user's data.
19
20Next, Google's OAuth 2.0 server sends a single-use authorization code to your application, either in the title bar of the browser or in the query string of an HTTP request to the local host. Your application exchanges this authorization code for an access token.
21
22Finally, your application can use the access token to call Google APIs.
23
24This flow is similar to the one shown in the [Using OAuth 2.0 for Web Server Applications](https://developers.google.com/api-client-library/python/auth/web-app), but with three differences:
25
26- When creating a client ID, you specify that your application is an Installed application. This results in a different value for the redirect_uri parameter.
27- The client ID and client secret obtained from the API Console are embedded in the source code of your application. In this context, the client secret is obviously not treated as a secret.
28- The authorization code can be returned to your application in the title bar of the browser or in the query string of an HTTP request to the local host.
29
30## Creating application credentials
31
32All applications that use OAuth 2.0 must have credentials that identify the application to the OAuth 2.0 server. Applications that have these credentials can access the APIs that you enabled for your project.
33
34To obtain application credentials for your project, complete these steps:
35
361. Open the [Credentials page](https://console.developers.google.com/apis/credentials) in the API Console.
371. If you haven't done so already, create your OAuth 2.0 credentials by clicking **Create new Client ID** under the **OAuth** heading and selecting the **Installed application** type. Next, look for your application's client ID and client secret in the relevant table.
38
39Download the client_secrets.json file and securely store it in a location that only your application can access.
40
41> **Important:** Do not store the client_secrets.json file in a publicly-accessible location, and if you share the source code to your application—for example, on GitHub—store the client_secrets.json file outside of your source tree to avoid inadvertently sharing your client credentials.
42
43## Configuring the client object
44
45Use the client application credentials that you created to configure a client object in your application. When you configure a client object, you specify the scopes your application needs to access, along with a redirect URI, which will handle the response from the OAuth 2.0 server.
46
47### Choosing a redirect URI
48
49When you create a client ID in the [Google API Console](https://console.developers.google.com/), two redirect_uri parameters are created for you: `urn:ietf:wg:oauth:2.0:oob` and `http://localhost`. The value your application uses determines how the authorization code is returned to your application.
50
51#### http://localhost
52
53This value signals to the Google Authorization Server that the authorization code should be returned as a query string parameter to the web server on the client. You can specify a port number without changing the [Google API Console](https://console.developers.google.com/) configuration. To receive the authorization code using this URI, your application must be listening on the local web server. This is possible on many, but not all, platforms. If your platform supports it, this is the recommended mechanism for obtaining the authorization code.
54
55> **Note:** In some cases, although it is possible to listen, other software (such as a Windows firewall) prevents delivery of the message without significant client configuration.
56
57#### urn:ietf:wg:oauth:2.0:oob
58
59This value signals to the Google Authorization Server that the authorization code should be returned in the title bar of the browser, with the page text prompting the user to copy the code and paste it in the application. This is useful when the client (such as a Windows application) cannot listen on an HTTP port without significant client configuration.
60
61When you use this value, your application can then detect that the page has loaded, and can read the title of the HTML page to obtain the authorization code. It is then up to your application to close the browser window if you want to ensure that the user never sees the page that contains the authorization code. The mechanism for doing this varies from platform to platform.
62
63If your platform doesn't allow you to detect that the page has loaded or read the title of the page, you can have the user paste the code back to your application, as prompted by the text in the confirmation page that the OAuth 2.0 server generates.
64
65#### urn:ietf:wg:oauth:2.0:oob:auto
66
67urn:ietf:wg:oauth:2.0:oob:auto
68This is identical to urn:ietf:wg:oauth:2.0:oob, but the text in the confirmation page that the OAuth 2.0 server generates won't instruct the user to copy the authorization code, but instead will simply ask the user to close the window.
69
70This is useful when your application reads the title of the HTML page (by checking window titles on the desktop, for example) to obtain the authorization code, but can't close the page on its own.
71
72### Creating the object
73
74To create a client object from the client_secrets.json file, use the `flow_from_clientsecrets` function. For example, to request read-only access to a user's Google Drive:
75
76```python
77from google_auth_oauthlib.flow import InstalledAppFlow
78
79flow = InstalledAppFlow.from_client_secrets_file(
80    'client_secret.json',
81    scopes=['https://www.googleapis.com/auth/drive.metadata.readonly'])
82```
83
84Your application uses the client object to perform OAuth 2.0 operations, such as generating authorization request URIs and applying access tokens to HTTP requests.
85
86## Sending users to Google's OAuth 2.0 server
87
88Use either the `run_console` or `run_local_server` function to direct the user to Google's OAuth 2.0 server:
89
90- The run_console function instructs the user to open the authorization URL in their browser. After the user authorizes the application, the authorization server displays a web page with an authorization code, which the user then pastes into the application. The authorization library automatically exchanges the code for an access token.
91
92    ```python
93    credentials = flow.run_console()
94    ```
95
96- The run_local_server function attempts to open the authorization URL in the user's browser. It also starts a local web server to listen for the authorization response. After the user completes the auth flow, the authorization server redirects the user's browser to the local web server. That server gets the authorization code from the browser and shuts down, then exchanges the code for an access token.
97
98    ```python
99    credentials = flow.run_local_server(host='localhost',
100        port=8080,
101        authorization_prompt_message='Please visit this URL: {url}',
102        success_message='The auth flow is complete; you may close this window.',
103        open_browser=True)
104    ```
105
106Google's OAuth 2.0 server authenticates the user and obtains consent from the user for your application to access the requested scopes.
107
108## Calling Google APIs
109
110Use the authorized `Http` object to call Google APIs by completing the following steps:
111
1121. 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 3 of the Drive API:
113
114    ```python
115    from googleapiclient.discovery import build
116
117    drive_service = build('drive', 'v3', credentials=credentials)
118    ```
119
1201. Make requests to the API service using the [interface provided by the service object](start.md#build). For example, to list the files in the authenticated user's Google Drive:
121
122    ```python
123    files = drive_service.files().list().execute()
124    ```
125
126## Complete example
127
128The following example requests access to the user's Google Drive files. If the user grants access, the code retrieves and prints a JSON-formatted list of the five Drive files that were most recently modified by the user.
129
130```python
131import os
132import pprint
133
134import google.oauth2.credentials
135
136from googleapiclient.discovery import build
137from googleapiclient.errors import HttpError
138from google_auth_oauthlib.flow import InstalledAppFlow
139
140pp = pprint.PrettyPrinter(indent=2)
141
142# The CLIENT_SECRETS_FILE variable specifies the name of a file that contains
143# the OAuth 2.0 information for this application, including its client_id and
144# client_secret.
145CLIENT_SECRETS_FILE = "client_secret.json"
146
147# This access scope grants read-only access to the authenticated user's Drive
148# account.
149SCOPES = ['https://www.googleapis.com/auth/drive.metadata.readonly']
150API_SERVICE_NAME = 'drive'
151API_VERSION = 'v3'
152
153def get_authenticated_service():
154  flow = InstalledAppFlow.from_client_secrets_file(CLIENT_SECRETS_FILE, SCOPES)
155  credentials = flow.run_console()
156  return build(API_SERVICE_NAME, API_VERSION, credentials = credentials)
157
158def list_drive_files(service, **kwargs):
159  results = service.files().list(
160    **kwargs
161  ).execute()
162
163  pp.pprint(results)
164
165if __name__ == '__main__':
166  # When running locally, disable OAuthlib's HTTPs verification. When
167  # running in production *do not* leave this option enabled.
168  os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1'
169  service = get_authenticated_service()
170  list_drive_files(service,
171                   orderBy='modifiedByMeTime desc',
172                   pageSize=5)
173```
174