blob: 947c4ac9dc9112d74111f614ffba4b98b1c025e0 [file] [log] [blame] [view]
Grant Timmerman5c11b0a2019-06-26 07:39:48 -07001# OAuth 2.0
2
3This document describes OAuth 2.0, when to use it, how to acquire client IDs, and how to use it with the Google APIs Client Library for Python.
4
5## OAuth 2.0 explained
6
7OAuth 2.0 is the authorization protocol used by Google APIs. It is summarized on the [Authentication](auth.md) page of this library's documentation, and there are other good references as well:
8
9* [The OAuth 2.0 Authorization Protocol](https://tools.ietf.org/html/rfc6749)
10* [Using OAuth 2.0 to Access Google APIs](https://developers.google.com/accounts/docs/OAuth2)
11
12The protocol is solving a complex problem, so it can be difficult to understand. This presentation explains the important concepts of the protocol, and introduces you to how the library is used at each step.
13
14## Acquiring client IDs and secrets
15
16You can get client IDs and secrets on the [API Access pane](https://console.developers.google.com/apis/credentials) of the Google APIs Console. There are different types of client IDs, so be sure to get the correct type for your application:
17
18* Web application client IDs
19* Installed application client IDs
20* [Service Account](https://developers.google.com/accounts/docs/OAuth2ServiceAccount) client IDs
21
22**Warning**: Keep your client secret private. If someone obtains your client secret, they could use it to consume your quota, incur charges against your Google APIs Console project, and request access to user data.
23
24## The oauth2client library
25
26The [oauth2client](http://oauth2client.readthedocs.org/en/latest/index.html) library is included with the Google APIs Client Library for Python. It handles all steps of the OAuth 2.0 protocol required for making API calls. It is available as a separate [package](https://pypi.python.org/pypi/oauth2client) if you only need an OAuth 2.0 library. The sections below describe important modules, classes, and functions of this library.
27
28## Flows
29
30The purpose of a `Flow` class is to acquire credentials that authorize your application access to user data. In order for a user to grant access, OAuth 2.0 steps require your application to potentially redirect their browser multiple times. A `Flow` object has functions that help your application take these steps and acquire credentials. `Flow` objects are only temporary and can be discarded once they have produced credentials, but they can also be [pickled](http://docs.python.org/library/pickle.html) and stored. This section describes the various methods to create and use `Flow` objects.
31
32**Note**: See the [Using Google App Engine](app-engine.md) and [Using Django](django.md) pages for platform-specific Flows.
33
34### flow_from_clientsecrets()
35
36The [oauth2client.client.flow_from_clientsecrets()](http://oauth2client.readthedocs.org/en/latest/source/oauth2client.client.html#oauth2client.client.flow_from_clientsecrets) method creates a `Flow` object from a [client_secrets.json](client_secrets.md) file. This [JSON](http://www.json.org/) formatted file stores your client ID, client secret, and other OAuth 2.0 parameters.
37
38The following shows how you can use `flow_from_clientsecrets()` to create a `Flow` object:
39
40```py
41from oauth2client.client import flow_from_clientsecrets
42...
43flow = flow_from_clientsecrets('path_to_directory/client_secrets.json',
44 scope='https://www.googleapis.com/auth/calendar',
45 redirect_uri='http://example.com/auth_return')
46```
47
48### OAuth2WebServerFlow
49
50Despite its name, the [oauth2client.client.OAuth2WebServerFlow](http://oauth2client.readthedocs.org/en/latest/source/oauth2client.client.html#oauth2client.client.OAuth2WebServerFlow) class is used for both installed and web applications. It is created by passing the client ID, client secret, and scope to its constructor: You provide the constructor with a `redirect_uri` parameter. This must be a URI handled by your application.
51
52```py
53from oauth2client.client import OAuth2WebServerFlow
54...
55flow = OAuth2WebServerFlow(client_id='your_client_id',
56 client_secret='your_client_secret',
57 scope='https://www.googleapis.com/auth/calendar',
58 redirect_uri='http://example.com/auth_return')
59```
60
61### step1_get_authorize_url()
62
63The [step1_get_authorize_url()](http://oauth2client.readthedocs.org/en/latest/source/oauth2client.client.html#oauth2client.client.OAuth2WebServerFlow.step1_get_authorize_url) function of the `Flow` class is used to generate the authorization server URI. Once you have the authorization server URI, redirect the user to it. The following is an example call to this function:
64
65```py
66auth_uri = flow.step1_get_authorize_url()
67# Redirect the user to auth_uri on your platform.
68```
69
70If the user has previously granted your application access, the authorization server immediately redirects again to `redirect_uri`. If the user has not yet granted access, the authorization server asks them to grant your application access. If they grant access, they get redirected to `redirect_uri` with a `code` query string parameter similar to the following:
71
72`http://example.com/auth_return/?code=kACAH-1Ng1MImB...AA7acjdY9pTD9M`
73
74If they deny access, they get redirected to `redirect_uri` with an `error` query string parameter similar to the following:
75
76`http://example.com/auth_return/?error=access_denied`
77
78### step2_exchange()
79
80The [step2_exchange()](http://oauth2client.readthedocs.org/en/latest/source/oauth2client.client.html#oauth2client.client.OAuth2WebServerFlow.step2_exchange) function of the `Flow` class exchanges an authorization code for a `Credentials` object. Pass the `code` provided by the authorization server redirection to this function:
81
82```py
83credentials = flow.step2_exchange(code)
84```
85
86## Credentials
87
88A `Credentials` object holds refresh and access tokens that authorize access to a single user's data. These objects are applied to `httplib2.Http` objects to authorize access. They only need to be applied once and can be stored. This section describes the various methods to create and use `Credentials` objects.
89
90**Note**: See the [Using Google App Engine](google-app-engine.md) and [Using Django](django.md) pages for platform-specific Credentials.
91
92### OAuth2Credentials
93
94The [oauth2client.client.OAuth2Credentials](http://oauth2client.readthedocs.org/en/latest/source/oauth2client.client.html#oauth2client.client.OAuth2Credentials) class holds OAuth 2.0 credentials that authorize access to a user's data. Normally, you do not create this object by calling its constructor. A `Flow` object can create one for you.
95
96### ServiceAccountCredentials
97
98The [oauth2client.service_account.ServiceAccountCredentials](http://oauth2client.readthedocs.org/en/latest/source/oauth2client.service_account.html) class is only used with [OAuth 2.0 Service Accounts](https://developers.google.com/accounts/docs/OAuth2ServiceAccount). No end-user is involved for these server-to-server API calls, so you can create this object directly without using a `Flow` object.
99
100### AccessTokenCredentials
101
102The [oauth2client.client.AccessTokenCredentials](http://oauth2client.readthedocs.org/en/latest/source/oauth2client.client.html#oauth2client.client.AccessTokenCredentials) class is used when you have already obtained an access token by some other means. You can create this object directly without using a `Flow` object.
103
104### authorize()
105
106Use the [authorize()](http://oauth2client.readthedocs.org/en/latest/source/oauth2client.client.html#oauth2client.client.Credentials.authorize) function of the `Credentials` class to apply necessary credential headers to all requests made by an [httplib2.Http](http://bitworking.org/projects/httplib2/doc/html/libhttplib2.html#httplib2.Http) instance:
107
108```py
109import httplib2
110...
111http = httplib2.Http()
112http = credentials.authorize(http)
113```
114
115Once an `httplib2.Http` object has been authorized, it is typically passed to the build function:
116
117```py
118from apiclient.discovery import build
119...
120service = build('calendar', 'v3', http=http)
121```
122
123## Storage
124
125A [oauth2client.client.Storage](http://oauth2client.readthedocs.org/en/latest/source/oauth2client.client.html#oauth2client.client.Storage) object stores and retrieves `Credentials` objects. This section describes the various methods to create and use `Storage` objects.
126
127**Note**: See the [Using Google App Engine](app-engine.md) and [Using Django](django.md) pages for platform-specific Storage.
128
129### file.Storage
130
131The [oauth2client.file.Storage](http://oauth2client.readthedocs.org/en/latest/source/oauth2client.file.html#oauth2client.file.Storage) class stores and retrieves a single `Credentials` object. The class supports locking such that multiple processes and threads can operate on a single store. The following shows how to open a file, save `Credentials` to it, and retrieve those credentials:
132
133```py
134from oauth2client.file import Storage
135...
136storage = Storage('_a_credentials_file_')
137storage.put(credentials)
138...
139credentials = storage.get()
140```
141
142### multistore_file
143
144The [oauth2client.contrib.multistore_file](http://oauth2client.readthedocs.org/en/latest/source/oauth2client.contrib.multistore_file.html) module allows multiple credentials to be stored. The credentials are keyed off of:
145
146* client ID
147* user agent
148* scope
149
150### keyring_storage
151
152The [oauth2client.contrib.keyring_storage](http://oauth2client.readthedocs.org/en/latest/source/oauth2client.contrib.keyring_storage.html) module allows a single `Credentials` object to be stored in a [password manager](http://en.wikipedia.org/wiki/Password_manager) if one is available. The credentials are keyed off of:
153
154* Name of the client application
155* User name
156
157```py
158from oauth2client.contrib.keyring_storage import Storage
159...
160storage = Storage('_application name_', '_user name_')
161storage.put(credentials)
162...
163credentials = storage.get()
164```
165
166## Command-line tools
167
168The [oauth2client.tools.run_flow()](http://oauth2client.readthedocs.org/en/latest/source/oauth2client.tools.html#oauth2client.tools.run_flow) function can be used by command-line applications to acquire credentials. It takes a `Flow` argument and attempts to open an authorization server page in the user's default web browser. The server asks the user to grant your application access to the user's data. If the user grants access, the run() function returns new credentials. The new credentials are also stored in the `Storage` argument, which updates the file associated with the `Storage` object.
169
170The [oauth2client.tools.run_flow()](http://oauth2client.readthedocs.org/en/latest/source/oauth2client.tools.html#oauth2client.tools.run_flow) function is controlled by command-line flags, and the Python standard library [argparse](http://docs.python.org/dev/library/argparse.html) module must be initialized at the start of your program. Argparse is included in Python 2.7+, and is available as a [separate package](https://pypi.python.org/pypi/argparse) for older versions. The following shows an example of how to use this function:
171
172```py
173import argparse
174from oauth2client import tools
175
176parser = argparse.ArgumentParser(parents=[tools.argparser])
177flags = parser.parse_args()
178...
179credentials = tools.run_flow(flow, storage, flags)
180```