oauth2client

Note

oauth2client is now deprecated. No more features will be added to the

libraries and the core team is turning down support. We recommend you use google-auth and oauthlib. For more details on the deprecation, see oauth2client deprecation.

making OAuth2 just a little less painful

oauth2client makes it easy to interact with OAuth2-protected resources, especially those related to Google APIs. You can also start with general information about using OAuth2 with Google APIs.

Getting started

We recommend installing via pip:

$ pip install --upgrade oauth2client

You can also install from source:

$ git clone https://github.com/google/oauth2client
$ cd oauth2client
$ python setup.py install

Using pypy

  • In order to use crypto libraries (e.g. for service accounts) you will need to install one of pycrypto or pyOpenSSL.

  • Using pycrypto with pypy will be in general problematic. If libgmp is installed on your machine, the pycrypto install will attempt to build _fastmath.c. However, this file uses CPython implementation details and hence can’t be built in pypy (as of pypy 2.6 and pycrypto 2.6.1). In order to install

    with_gmp=no pip install --upgrade pycrypto
    

    See discussions on the pypy issue tracker and the pycrypto issue tracker.

  • Using pyOpenSSL with versions of pypy before 2.6 may be in general problematic since pyOpenSSL depends on the cryptography library. For versions of cryptography before 1.0, importing pyOpenSSL with it caused massive startup costs. In order to address this slow startup, cryptography 1.0 made some changes in how it used cffi when means it can’t be used on versions of pypy before 2.6.

    The default version of pypy you get when installed

    apt-get install pypy pypy-dev
    

    on Ubuntu 14.04 is 2.2.1. In order to upgrade, you’ll need to use the pypy/ppa PPA:

    apt-get purge pypy pypy-dev
    add-apt-repository ppa:pypy/ppa
    apt-get update
    apt-get install pypy pypy-dev
    

Library Documentation

Contributing

Please see the contributing page for more information. In particular, we love pull requests – but please make sure to sign the contributor license agreement.

oauth2client package

Subpackages

oauth2client.contrib package
Subpackages
oauth2client.contrib.django_util package
Submodules
oauth2client.contrib.django_util.apps module
oauth2client.contrib.django_util.decorators module
oauth2client.contrib.django_util.models module
oauth2client.contrib.django_util.signals module
oauth2client.contrib.django_util.site module
oauth2client.contrib.django_util.storage module
oauth2client.contrib.django_util.views module
Module contents
Submodules
oauth2client.contrib.appengine module

Utilities for Google App Engine

Utilities for making it easier to use OAuth 2.0 on Google App Engine.

class oauth2client.contrib.appengine.AppAssertionCredentials(**kwargs)[source]

Bases: oauth2client.client.AssertionCredentials

Credentials object for App Engine Assertion Grants

This object will allow an App Engine application to identify itself to Google and other OAuth 2.0 servers that can verify assertions. It can be used for the purpose of accessing data stored under an account assigned to the App Engine application itself.

This credential does not require a flow to instantiate because it represents a two legged flow, and therefore has all of the required information to generate and refresh its own access tokens.

create_scoped(scopes)[source]

Create a Credentials object for the given scopes.

The Credentials type is preserved.

create_scoped_required()[source]

Whether this Credentials object is scopeless.

create_scoped(scopes) method needs to be called in order to create a Credentials object for API calls.

classmethod from_json(json_data)[source]

Instantiate a Credentials object from a JSON description of it.

The JSON should have been produced by calling .to_json() on the object.

Parameters:json_data – string or bytes, JSON to deserialize.
Returns:An instance of a Credentials subclass.
serialization_data
service_account_email

Get the email for the current service account.

Returns:string, The email associated with the Google App Engine service account.
sign_blob(blob)[source]

Cryptographically sign a blob (of bytes).

Implements abstract method oauth2client.client.AssertionCredentials.sign_blob().

Parameters:blob – bytes, Message to be signed.
Returns:tuple, A pair of the private key ID used to sign the blob and the signed contents.
class oauth2client.contrib.appengine.OAuth2Decorator(**kwargs)[source]

Bases: object

Utility for making OAuth 2.0 easier.

Instantiate and then use with oauth_required or oauth_aware as decorators on webapp.RequestHandler methods.

decorator = OAuth2Decorator(
    client_id='837...ent.com',
    client_secret='Qh...wwI',
    scope='https://www.googleapis.com/auth/plus')

class MainHandler(webapp.RequestHandler):
    @decorator.oauth_required
    def get(self):
        http = decorator.http()
        # http is authorized with the user's Credentials and can be
        # used in API calls
authorize_url()[source]

Returns the URL to start the OAuth dance.

Must only be called from with a webapp.RequestHandler subclassed method that had been decorated with either @oauth_required or @oauth_aware.

callback_application()[source]

WSGI application for handling the OAuth 2.0 redirect callback.

If you need finer grained control use callback_handler which returns just the webapp.RequestHandler.

Returns:A webapp.WSGIApplication that handles the redirect back from the server during the OAuth 2.0 dance.
callback_handler()[source]

RequestHandler for the OAuth 2.0 redirect callback.

Usage:

app = webapp.WSGIApplication([
    ('/index', MyIndexHandler),
    ...,
    (decorator.callback_path, decorator.callback_handler())
])
Returns:A webapp.RequestHandler that handles the redirect back from the server during the OAuth 2.0 dance.
callback_path

The absolute path where the callback will occur.

Note this is the absolute path, not the absolute URI, that will be calculated by the decorator at runtime. See callback_handler() for how this should be used.

Returns:The callback path as a string.
credentials

A thread local Credentials object.

Returns:A client.Credentials object, or None if credentials hasn’t been set in this thread yet, which may happen when calling has_credentials inside oauth_aware.
flow

A thread local Flow object.

Returns:A credentials.Flow object, or None if the flow hasn’t been set in this thread yet, which happens in _create_flow() since Flows are created lazily.
get_credentials()[source]

A thread local Credentials object.

Returns:A client.Credentials object, or None if credentials hasn’t been set in this thread yet, which may happen when calling has_credentials inside oauth_aware.
get_flow()[source]

A thread local Flow object.

Returns:A credentials.Flow object, or None if the flow hasn’t been set in this thread yet, which happens in _create_flow() since Flows are created lazily.
has_credentials()[source]

True if for the logged in user there are valid access Credentials.

Must only be called from with a webapp.RequestHandler subclassed method that had been decorated with either @oauth_required or @oauth_aware.

http(*args, **kwargs)[source]

Returns an authorized http instance.

Must only be called from within an @oauth_required decorated method, or from within an @oauth_aware decorated method where has_credentials() returns True.

Parameters:
  • *args – Positional arguments passed to httplib2.Http constructor.
  • **kwargs – Positional arguments passed to httplib2.Http constructor.
oauth_aware(method)[source]

Decorator that sets up for OAuth 2.0 dance, but doesn’t do it.

Does all the setup for the OAuth dance, but doesn’t initiate it. This decorator is useful if you want to create a page that knows whether or not the user has granted access to this application. From within a method decorated with @oauth_aware the has_credentials() and authorize_url() methods can be called.

Parameters:method – callable, to be decorated method of a webapp.RequestHandler instance.
oauth_required(method)[source]

Decorator that starts the OAuth 2.0 dance.

Starts the OAuth dance for the logged in user if they haven’t already granted access for this application.

Parameters:method – callable, to be decorated method of a webapp.RequestHandler instance.
set_credentials(credentials)[source]
set_flow(flow)[source]
class oauth2client.contrib.appengine.OAuth2DecoratorFromClientSecrets(**kwargs)[source]

Bases: oauth2client.contrib.appengine.OAuth2Decorator

An OAuth2Decorator that builds from a clientsecrets file.

Uses a clientsecrets file as the source for all the information when constructing an OAuth2Decorator.

decorator = OAuth2DecoratorFromClientSecrets(
    os.path.join(os.path.dirname(__file__), 'client_secrets.json')
    scope='https://www.googleapis.com/auth/plus')

class MainHandler(webapp.RequestHandler):
    @decorator.oauth_required
    def get(self):
        http = decorator.http()
        # http is authorized with the user's Credentials and can be
        # used in API calls
class oauth2client.contrib.appengine.StorageByKeyName(**kwargs)[source]

Bases: oauth2client.client.Storage

Store and retrieve a credential to and from the App Engine datastore.

This Storage helper presumes the Credentials have been stored as a CredentialsProperty or CredentialsNDBProperty on a datastore model class, and that entities are stored by key_name.

locked_delete
locked_get
locked_put
oauth2client.contrib.appengine.oauth2decorator_from_clientsecrets(*args, **kwargs)[source]

Creates an OAuth2Decorator populated from a clientsecrets file.

Parameters:
  • filename – string, File name of client secrets.
  • scope – string or list of strings, scope(s) of the credentials being requested.
  • message – string, A friendly string to display to the user if the clientsecrets file is missing or invalid. The message may contain HTML and will be presented on the web interface for any method that uses the decorator.
  • cache – An optional cache service client that implements get() and set() methods. See clientsecrets.loadfile() for details.

Returns: An OAuth2Decorator

oauth2client.contrib.appengine.xsrf_secret_key()[source]

Return the secret key for use for XSRF protection.

If the Site entity does not have a secret key, this method will also create one and persist it.

Returns:The secret key.
oauth2client.contrib.devshell module

OAuth 2.0 utitilies for Google Developer Shell environment.

exception oauth2client.contrib.devshell.CommunicationError[source]

Bases: oauth2client.contrib.devshell.Error

Errors for communication with the Developer Shell server.

class oauth2client.contrib.devshell.CredentialInfoResponse(json_string)[source]

Bases: object

Credential information response from Developer Shell server.

The credential information response from Developer Shell socket is a PBLite-formatted JSON array with fields encoded by their index in the array:

  • Index 0 - user email
  • Index 1 - default project ID. None if the project context is not known.
  • Index 2 - OAuth2 access token. None if there is no valid auth context.
  • Index 3 - Seconds until the access token expires. None if not present.
class oauth2client.contrib.devshell.DevshellCredentials(user_agent=None)[source]

Bases: oauth2client.client.GoogleCredentials

Credentials object for Google Developer Shell environment.

This object will allow a Google Developer Shell session to identify its user to Google and other OAuth 2.0 servers that can verify assertions. It can be used for the purpose of accessing data stored under the user account.

This credential does not require a flow to instantiate because it represents a two legged flow, and therefore has all of the required information to generate and refresh its own access tokens.

classmethod from_json(json_data)[source]

Instantiate a Credentials object from a JSON description of it.

The JSON should have been produced by calling .to_json() on the object.

Parameters:json_data – string or bytes, JSON to deserialize.
Returns:An instance of a Credentials subclass.
project_id
serialization_data
user_email
exception oauth2client.contrib.devshell.Error[source]

Bases: exceptions.Exception

Errors for this module.

exception oauth2client.contrib.devshell.NoDevshellServer[source]

Bases: oauth2client.contrib.devshell.Error

Error when no Developer Shell server can be contacted.

oauth2client.contrib.dictionary_storage module

Dictionary storage for OAuth2 Credentials.

class oauth2client.contrib.dictionary_storage.DictionaryStorage(dictionary, key, lock=None)[source]

Bases: oauth2client.client.Storage

Store and retrieve credentials to and from a dictionary-like object.

Parameters:
  • dictionary – A dictionary or dictionary-like object.
  • key – A string or other hashable. The credentials will be stored in dictionary[key].
  • lock – An optional threading.Lock-like object. The lock will be acquired before anything is written or read from the dictionary.
locked_delete()[source]

Remove the credentials from the dictionary, if they exist.

locked_get()[source]

Retrieve the credentials from the dictionary, if they exist.

Returns: A oauth2client.client.OAuth2Credentials instance.

locked_put(credentials)[source]

Save the credentials to the dictionary.

Parameters:credentials – A oauth2client.client.OAuth2Credentials instance.
oauth2client.contrib.flask_util module

Utilities for the Flask web framework

Provides a Flask extension that makes using OAuth2 web server flow easier. The extension includes views that handle the entire auth flow and a @required decorator to automatically ensure that user credentials are available.

Configuration

To configure, you’ll need a set of OAuth2 web application credentials from the Google Developer’s Console.

from oauth2client.contrib.flask_util import UserOAuth2

app = Flask(__name__)

app.config['SECRET_KEY'] = 'your-secret-key'

app.config['GOOGLE_OAUTH2_CLIENT_SECRETS_FILE'] = 'client_secrets.json'

# or, specify the client id and secret separately
app.config['GOOGLE_OAUTH2_CLIENT_ID'] = 'your-client-id'
app.config['GOOGLE_OAUTH2_CLIENT_SECRET'] = 'your-client-secret'

oauth2 = UserOAuth2(app)
Usage

Once configured, you can use the UserOAuth2.required() decorator to ensure that credentials are available within a view.

 # Note that app.route should be the outermost decorator.
 @app.route('/needs_credentials')
 @oauth2.required
 def example():
     # http is authorized with the user's credentials and can be used
     # to make http calls.
     http = oauth2.http()

     # Or, you can access the credentials directly
     credentials = oauth2.credentials

If you want credentials to be optional for a view, you can leave the decorator off and use UserOAuth2.has_credentials() to check.

 @app.route('/optional')
 def optional():
     if oauth2.has_credentials():
         return 'Credentials found!'
     else:
         return 'No credentials!'

When credentials are available, you can use UserOAuth2.email and UserOAuth2.user_id to access information from the ID Token, if available.

 @app.route('/info')
 @oauth2.required
 def info():
     return "Hello, {} ({})".format(oauth2.email, oauth2.user_id)
URLs & Trigging Authorization

The extension will add two new routes to your application:

  • "oauth2.authorize" -> /oauth2authorize
  • "oauth2.callback" -> /oauth2callback

When configuring your OAuth2 credentials on the Google Developer’s Console, be sure to add http[s]://[your-app-url]/oauth2callback as an authorized callback url.

Typically you don’t not need to use these routes directly, just be sure to decorate any views that require credentials with @oauth2.required. If needed, you can trigger authorization at any time by redirecting the user to the URL returned by UserOAuth2.authorize_url().

 @app.route('/login')
 def login():
     return oauth2.authorize_url("/")
Incremental Auth

This extension also supports Incremental Auth. To enable it, configure the extension with include_granted_scopes.

oauth2 = UserOAuth2(app, include_granted_scopes=True)

Then specify any additional scopes needed on the decorator, for example:

 @app.route('/drive')
 @oauth2.required(scopes=["https://www.googleapis.com/auth/drive"])
 def requires_drive():
     ...

 @app.route('/calendar')
 @oauth2.required(scopes=["https://www.googleapis.com/auth/calendar"])
 def requires_calendar():
     ...

The decorator will ensure that the the user has authorized all specified scopes before allowing them to access the view, and will also ensure that credentials do not lose any previously authorized scopes.

Storage

By default, the extension uses a Flask session-based storage solution. This means that credentials are only available for the duration of a session. It also means that with Flask’s default configuration, the credentials will be visible in the session cookie. It’s highly recommended to use database-backed session and to use https whenever handling user credentials.

If you need the credentials to be available longer than a user session or available outside of a request context, you will need to implement your own oauth2client.Storage.

class oauth2client.contrib.flask_util.UserOAuth2(app=None, *args, **kwargs)[source]

Bases: object

Flask extension for making OAuth 2.0 easier.

Configuration values:

  • GOOGLE_OAUTH2_CLIENT_SECRETS_FILE path to a client secrets json file, obtained from the credentials screen in the Google Developers console.
  • GOOGLE_OAUTH2_CLIENT_ID the oauth2 credentials’ client ID. This is only needed if GOOGLE_OAUTH2_CLIENT_SECRETS_FILE is not specified.
  • GOOGLE_OAUTH2_CLIENT_SECRET the oauth2 credentials’ client secret. This is only needed if GOOGLE_OAUTH2_CLIENT_SECRETS_FILE is not specified.

If app is specified, all arguments will be passed along to init_app.

If no app is specified, then you should call init_app in your application factory to finish initialization.

authorize_url(return_url, **kwargs)[source]

Creates a URL that can be used to start the authorization flow.

When the user is directed to the URL, the authorization flow will begin. Once complete, the user will be redirected to the specified return URL.

Any kwargs are passed into the flow constructor.

authorize_view()[source]

Flask view that starts the authorization flow.

Starts flow by redirecting the user to the OAuth2 provider.

callback_view()[source]

Flask view that handles the user’s return from OAuth2 provider.

On return, exchanges the authorization code for credentials and stores the credentials.

credentials

The credentials for the current user or None if unavailable.

email

Returns the user’s email address or None if there are no credentials.

The email address is provided by the current credentials’ id_token. This should not be used as unique identifier as the user can change their email. If you need a unique identifier, use user_id.

has_credentials()[source]

Returns True if there are valid credentials for the current user.

http(*args, **kwargs)[source]

Returns an authorized http instance.

Can only be called if there are valid credentials for the user, such as inside of a view that is decorated with @required.

Parameters:
  • *args – Positional arguments passed to httplib2.Http constructor.
  • **kwargs – Positional arguments passed to httplib2.Http constructor.
Raises:

ValueError if no credentials are available.

init_app(app, scopes=None, client_secrets_file=None, client_id=None, client_secret=None, authorize_callback=None, storage=None, **kwargs)[source]

Initialize this extension for the given app.

Parameters:
  • app – A Flask application.
  • scopes – Optional list of scopes to authorize.
  • client_secrets_file – Path to a file containing client secrets. You can also specify the GOOGLE_OAUTH2_CLIENT_SECRETS_FILE config value.
  • client_id – If not specifying a client secrets file, specify the OAuth2 client id. You can also specify the GOOGLE_OAUTH2_CLIENT_ID config value. You must also provide a client secret.
  • client_secret – The OAuth2 client secret. You can also specify the GOOGLE_OAUTH2_CLIENT_SECRET config value.
  • authorize_callback – A function that is executed after successful user authorization.
  • storage – A oauth2client.client.Storage subclass for storing the credentials. By default, this is a Flask session based storage.
  • kwargs – Any additional args are passed along to the Flow constructor.
required(decorated_function=None, scopes=None, **decorator_kwargs)[source]

Decorator to require OAuth2 credentials for a view.

If credentials are not available for the current user, then they will be redirected to the authorization flow. Once complete, the user will be redirected back to the original page.

user_id

Returns the a unique identifier for the user

Returns None if there are no credentials.

The id is provided by the current credentials’ id_token.

oauth2client.contrib.gce module

Utilities for Google Compute Engine

Utilities for making it easier to use OAuth 2.0 on Google Compute Engine.

class oauth2client.contrib.gce.AppAssertionCredentials(email=None, *args, **kwargs)[source]

Bases: oauth2client.client.AssertionCredentials

Credentials object for Compute Engine Assertion Grants

This object will allow a Compute Engine instance to identify itself to Google and other OAuth 2.0 servers that can verify assertions. It can be used for the purpose of accessing data stored under an account assigned to the Compute Engine instance itself.

This credential does not require a flow to instantiate because it represents a two legged flow, and therefore has all of the required information to generate and refresh its own access tokens.

Note that service_account_email and scopes will both return None until the credentials have been refreshed. To check whether credentials have previously been refreshed use invalid.

create_scoped_required()[source]

Whether this Credentials object is scopeless.

create_scoped(scopes) method needs to be called in order to create a Credentials object for API calls.

classmethod from_json(json_data)[source]

Instantiate a Credentials object from a JSON description of it.

The JSON should have been produced by calling .to_json() on the object.

Parameters:json_data – string or bytes, JSON to deserialize.
Returns:An instance of a Credentials subclass.
retrieve_scopes(http)[source]

Retrieves the canonical list of scopes for this access token.

Overrides client.Credentials.retrieve_scopes. Fetches scopes info from the metadata server.

Parameters:http – httplib2.Http, an http object to be used to make the refresh request.
Returns:A set of strings containing the canonical list of scopes.
serialization_data
sign_blob(blob)[source]

Cryptographically sign a blob (of bytes).

This method is provided to support a common interface, but the actual key used for a Google Compute Engine service account is not available, so it can’t be used to sign content.

Parameters:blob – bytes, Message to be signed.
Raises:NotImplementedError, always.
to_json()[source]

Creating a JSON representation of an instance of Credentials.

Returns:string, a JSON representation of this instance, suitable to pass to from_json().
oauth2client.contrib.keyring_storage module

A keyring based Storage.

A Storage for Credentials that uses the keyring module.

class oauth2client.contrib.keyring_storage.Storage(service_name, user_name)[source]

Bases: oauth2client.client.Storage

Store and retrieve a single credential to and from the keyring.

To use this module you must have the keyring module installed. See <http://pypi.python.org/pypi/keyring/>. This is an optional module and is not installed with oauth2client by default because it does not work on all the platforms that oauth2client supports, such as Google App Engine.

The keyring module <http://pypi.python.org/pypi/keyring/> is a cross-platform library for access the keyring capabilities of the local system. The user will be prompted for their keyring password when this module is used, and the manner in which the user is prompted will vary per platform.

Usage:

from oauth2client import keyring_storage

s = keyring_storage.Storage('name_of_application', 'user1')
credentials = s.get()
locked_delete()[source]

Delete Credentials file.

Parameters:credentials – Credentials, the credentials to store.
locked_get()[source]

Retrieve Credential from file.

Returns:oauth2client.client.Credentials
locked_put(credentials)[source]

Write Credentials to file.

Parameters:credentials – Credentials, the credentials to store.
oauth2client.contrib.multiprocess_file_storage module
oauth2client.contrib.sqlalchemy module
oauth2client.contrib.xsrfutil module

Helper methods for creating & verifying XSRF tokens.

oauth2client.contrib.xsrfutil.generate_token(*args, **kwargs)[source]

Generates a URL-safe token for the given user, action, time tuple.

Parameters:
  • key – secret key to use.
  • user_id – the user ID of the authenticated user.
  • action_id – a string identifier of the action they requested authorization for.
  • when – the time in seconds since the epoch at which the user was authorized for this action. If not set the current time is used.
Returns:

A string XSRF protection token.

oauth2client.contrib.xsrfutil.validate_token(*args, **kwargs)[source]

Validates that the given token authorizes the user for the action.

Tokens are invalid if the time of issue is too old or if the token does not match what generateToken outputs (i.e. the token was forged).

Parameters:
  • key – secret key to use.
  • token – a string of the token generated by generateToken.
  • user_id – the user ID of the authenticated user.
  • action_id – a string identifier of the action they requested authorization for.
Returns:

A boolean - True if the user is authorized for the action, False otherwise.

Module contents

Contributed modules.

Contrib contains modules that are not considered part of the core oauth2client library but provide additional functionality. These modules are intended to make it easier to use oauth2client.

Submodules

oauth2client.client module

An OAuth 2.0 client.

Tools for interacting with OAuth 2.0 protected resources.

class oauth2client.client.AccessTokenCredentials(access_token, user_agent, revoke_uri=None)[source]

Bases: oauth2client.client.OAuth2Credentials

Credentials object for OAuth 2.0.

Credentials can be applied to an httplib2.Http object using the authorize() method, which then signs each request from that object with the OAuth 2.0 access token. This set of credentials is for the use case where you have acquired an OAuth 2.0 access_token from another place such as a JavaScript client or another web application, and wish to use it from Python. Because only the access_token is present it can not be refreshed and will in time expire.

AccessTokenCredentials objects may be safely pickled and unpickled.

Usage:

credentials = AccessTokenCredentials('<an access token>',
    'my-user-agent/1.0')
http = httplib2.Http()
http = credentials.authorize(http)
Raises:AccessTokenCredentialsExpired – raised when the access_token expires or is revoked.
classmethod from_json(json_data)[source]

Instantiate a Credentials object from a JSON description of it.

The JSON should have been produced by calling .to_json() on the object.

Parameters:json_data – string or bytes, JSON to deserialize.
Returns:An instance of a Credentials subclass.
exception oauth2client.client.AccessTokenCredentialsError[source]

Bases: oauth2client.client.Error

Having only the access_token means no refresh is possible.

class oauth2client.client.AccessTokenInfo(access_token, expires_in)

Bases: tuple

access_token

Alias for field number 0

expires_in

Alias for field number 1

exception oauth2client.client.AccessTokenRefreshError[source]

Bases: oauth2client.client.Error

Error trying to refresh an expired access token.

exception oauth2client.client.ApplicationDefaultCredentialsError[source]

Bases: oauth2client.client.Error

Error retrieving the Application Default Credentials.

class oauth2client.client.AssertionCredentials(**kwargs)[source]

Bases: oauth2client.client.GoogleCredentials

Abstract Credentials object used for OAuth 2.0 assertion grants.

This credential does not require a flow to instantiate because it represents a two legged flow, and therefore has all of the required information to generate and refresh its own access tokens. It must be subclassed to generate the appropriate assertion string.

AssertionCredentials objects may be safely pickled and unpickled.

sign_blob(blob)[source]

Cryptographically sign a blob (of bytes).

Parameters:blob – bytes, Message to be signed.
Returns:tuple, A pair of the private key ID used to sign the blob and the signed contents.
class oauth2client.client.Credentials[source]

Bases: object

Base class for all Credentials objects.

Subclasses must define an authorize() method that applies the credentials to an HTTP transport.

Subclasses must also specify a classmethod named ‘from_json’ that takes a JSON string as input and returns an instantiated Credentials object.

NON_SERIALIZED_MEMBERS = frozenset(['store'])
apply(headers)[source]

Add the authorization to the headers.

Parameters:headers – dict, the headers to add the Authorization header to.
authorize(http)[source]

Take an httplib2.Http instance (or equivalent) and authorizes it.

Authorizes it for the set of credentials, usually by replacing http.request() with a method that adds in the appropriate headers and then delegates to the original Http.request() method.

Parameters:http – httplib2.Http, an http object to be used to make the refresh request.
classmethod from_json(unused_data)[source]

Instantiate a Credentials object from a JSON description of it.

The JSON should have been produced by calling .to_json() on the object.

Parameters:unused_data – dict, A deserialized JSON object.
Returns:An instance of a Credentials subclass.
classmethod new_from_json(json_data)[source]

Utility class method to instantiate a Credentials subclass from JSON.

Expects the JSON string to have been produced by to_json().

Parameters:json_data – string or bytes, JSON from to_json().
Returns:An instance of the subclass of Credentials that was serialized with to_json().
refresh(http)[source]

Forces a refresh of the access_token.

Parameters:http – httplib2.Http, an http object to be used to make the refresh request.
revoke(http)[source]

Revokes a refresh_token and makes the credentials void.

Parameters:http – httplib2.Http, an http object to be used to make the revoke request.
to_json()[source]

Creating a JSON representation of an instance of Credentials.

Returns:string, a JSON representation of this instance, suitable to pass to from_json().
exception oauth2client.client.CryptoUnavailableError[source]

Bases: oauth2client.client.Error, exceptions.NotImplementedError

Raised when a crypto library is required, but none is available.

class oauth2client.client.DeviceFlowInfo[source]

Bases: oauth2client.client.DeviceFlowInfo

Intermediate information the OAuth2 for devices flow.

classmethod FromResponse(response)[source]

Create a DeviceFlowInfo from a server response.

The response should be a dict containing entries as described here:

http://tools.ietf.org/html/draft-ietf-oauth-v2-05#section-3.7.1

exception oauth2client.client.Error[source]

Bases: exceptions.Exception

Base error for this module.

class oauth2client.client.Flow[source]

Bases: object

Base class for all Flow objects.

exception oauth2client.client.FlowExchangeError[source]

Bases: oauth2client.client.Error

Error trying to exchange an authorization grant for an access token.

class oauth2client.client.GoogleCredentials(access_token, client_id, client_secret, refresh_token, token_expiry, token_uri, user_agent, revoke_uri='https://accounts.google.com/o/oauth2/revoke')[source]

Bases: oauth2client.client.OAuth2Credentials

Application Default Credentials for use in calling Google APIs.

The Application Default Credentials are being constructed as a function of the environment where the code is being run. More details can be found on this page: https://developers.google.com/accounts/docs/application-default-credentials

Here is an example of how to use the Application Default Credentials for a service that requires authentication:

from googleapiclient.discovery import build
from oauth2client.client import GoogleCredentials

credentials = GoogleCredentials.get_application_default()
service = build('compute', 'v1', credentials=credentials)

PROJECT = 'bamboo-machine-422'
ZONE = 'us-central1-a'
request = service.instances().list(project=PROJECT, zone=ZONE)
response = request.execute()

print(response)
NON_SERIALIZED_MEMBERS = frozenset(['_private_key', 'store'])

Members that aren’t serialized when object is converted to JSON.

create_scoped(scopes)[source]

Create a Credentials object for the given scopes.

The Credentials type is preserved.

create_scoped_required()[source]

Whether this Credentials object is scopeless.

create_scoped(scopes) method needs to be called in order to create a Credentials object for API calls.

classmethod from_json(json_data)[source]

Instantiate a Credentials object from a JSON description of it.

The JSON should have been produced by calling .to_json() on the object.

Parameters:json_data – string or bytes, JSON to deserialize.
Returns:An instance of a Credentials subclass.
static from_stream(credential_filename)[source]

Create a Credentials object by reading information from a file.

It returns an object of type GoogleCredentials.

Parameters:credential_filename – the path to the file from where the credentials are to be read
Raises:ApplicationDefaultCredentialsError – raised when the credentials fail to be retrieved.
static get_application_default()[source]

Get the Application Default Credentials for the current environment.

Raises:ApplicationDefaultCredentialsError – raised when the credentials fail to be retrieved.
serialization_data

Get the fields and values identifying the current credentials.

exception oauth2client.client.HttpAccessTokenRefreshError(*args, **kwargs)[source]

Bases: oauth2client.client.AccessTokenRefreshError

Error (with HTTP status) trying to refresh an expired access token.

exception oauth2client.client.NonAsciiHeaderError[source]

Bases: oauth2client.client.Error

Header names and values must be ASCII strings.

class oauth2client.client.OAuth2Credentials(**kwargs)[source]

Bases: oauth2client.client.Credentials

Credentials object for OAuth 2.0.

Credentials can be applied to an httplib2.Http object using the authorize() method, which then adds the OAuth 2.0 access token to each request.

OAuth2Credentials objects may be safely pickled and unpickled.

access_token_expired

True if the credential is expired or invalid.

If the token_expiry isn’t set, we assume the token doesn’t expire.

apply(headers)[source]

Add the authorization to the headers.

Parameters:headers – dict, the headers to add the Authorization header to.
authorize(http)[source]

Authorize an httplib2.Http instance with these credentials.

The modified http.request method will add authentication headers to each request and will refresh access_tokens when a 401 is received on a request. In addition the http.request method has a credentials property, http.request.credentials, which is the Credentials object that authorized it.

Parameters:http – An instance of httplib2.Http or something that acts like it.
Returns:A modified instance of http that was passed in.

Example:

h = httplib2.Http()
h = credentials.authorize(h)

You can’t create a new OAuth subclass of httplib2.Authentication because it never gets passed the absolute URI, which is needed for signing. So instead we have to overload ‘request’ with a closure that adds in the Authorization header and then calls the original version of ‘request()’.

classmethod from_json(json_data)[source]

Instantiate a Credentials object from a JSON description of it.

The JSON should have been produced by calling .to_json() on the object.

Parameters:json_data – string or bytes, JSON to deserialize.
Returns:An instance of a Credentials subclass.
get_access_token(http=None)[source]

Return the access token and its expiration information.

If the token does not exist, get one. If the token expired, refresh it.

has_scopes(scopes)[source]

Verify that the credentials are authorized for the given scopes.

Returns True if the credentials authorized scopes contain all of the scopes given.

Parameters:scopes – list or string, the scopes to check.

Notes

There are cases where the credentials are unaware of which scopes are authorized. Notably, credentials obtained and stored before this code was added will not have scopes, AccessTokenCredentials do not have scopes. In both cases, you can use refresh_scopes() to obtain the canonical set of scopes.

refresh(http)[source]

Forces a refresh of the access_token.

Parameters:http – httplib2.Http, an http object to be used to make the refresh request.
retrieve_scopes(http)[source]

Retrieves the canonical list of scopes for this access token.

Gets the scopes from the OAuth2 provider.

Parameters:http – httplib2.Http, an http object to be used to make the refresh request.
Returns:A set of strings containing the canonical list of scopes.
revoke(http)[source]

Revokes a refresh_token and makes the credentials void.

Parameters:http – httplib2.Http, an http object to be used to make the revoke request.
set_store(store)[source]

Set the Storage for the credential.

Parameters:store – Storage, an implementation of Storage object. This is needed to store the latest access_token if it has expired and been refreshed. This implementation uses locking to check for updates before updating the access_token.
exception oauth2client.client.OAuth2DeviceCodeError[source]

Bases: oauth2client.client.Error

Error trying to retrieve a device code.

class oauth2client.client.OAuth2WebServerFlow(**kwargs)[source]

Bases: oauth2client.client.Flow

Does the Web Server Flow for OAuth 2.0.

OAuth2WebServerFlow objects may be safely pickled and unpickled.

step1_get_authorize_url(**kwargs)[source]

Returns a URI to redirect to the provider.

Parameters:
  • redirect_uri – string, Either the string ‘urn:ietf:wg:oauth:2.0:oob’ for a non-web-based application, or a URI that handles the callback from the authorization server. This parameter is deprecated, please move to passing the redirect_uri in via the constructor.
  • state – string, Opaque state string which is passed through the OAuth2 flow and returned to the client as a query parameter in the callback.
Returns:

A URI as a string to redirect the user to begin the authorization flow.

step1_get_device_and_user_codes(**kwargs)[source]

Returns a user code and the verification URL where to enter it

Returns:A user code as a string for the user to authorize the application An URL as a string where the user has to enter the code
step2_exchange(**kwargs)[source]

Exchanges a code for OAuth2Credentials.

Parameters:
  • code – string, a dict-like object, or None. For a non-device flow, this is either the response code as a string, or a dictionary of query parameters to the redirect_uri. For a device flow, this should be None.
  • http – httplib2.Http, optional http instance to use when fetching credentials.
  • device_flow_info – DeviceFlowInfo, return value from step1 in the case of a device flow.
Returns:

An OAuth2Credentials object that can be used to authorize requests.

Raises:
  • FlowExchangeError – if a problem occurred exchanging the code for a refresh_token.
  • ValueError – if code and device_flow_info are both provided or both missing.
class oauth2client.client.SETTINGS[source]

Bases: object

Settings namespace for globally defined values.

env_name = None
class oauth2client.client.Storage(lock=None)[source]

Bases: object

Base class for all Storage objects.

Store and retrieve a single credential. This class supports locking such that multiple processes and threads can operate on a single store.

acquire_lock()[source]

Acquires any lock necessary to access this Storage.

This lock is not reentrant.

delete()[source]

Delete credential.

Frees any resources associated with storing the credential. The Storage lock must not be held when this is called.

Returns:None
get()[source]

Retrieve credential.

The Storage lock must not be held when this is called.

Returns:oauth2client.client.Credentials
locked_delete()[source]

Delete a credential.

The Storage lock must be held when this is called.

locked_get()[source]

Retrieve credential.

The Storage lock must be held when this is called.

Returns:oauth2client.client.Credentials
locked_put(credentials)[source]

Write a credential.

The Storage lock must be held when this is called.

Parameters:credentials – Credentials, the credentials to store.
put(credentials)[source]

Write a credential.

The Storage lock must be held when this is called.

Parameters:credentials – Credentials, the credentials to store.
release_lock()[source]

Release the Storage lock.

Trying to release a lock that isn’t held will result in a RuntimeError in the case of a threading.Lock or multiprocessing.Lock.

exception oauth2client.client.TokenRevokeError[source]

Bases: oauth2client.client.Error

Error trying to revoke a token.

exception oauth2client.client.UnknownClientSecretsFlowError[source]

Bases: oauth2client.client.Error

The client secrets file called for an unknown type of OAuth 2.0 flow.

exception oauth2client.client.VerifyJwtTokenError[source]

Bases: oauth2client.client.Error

Could not retrieve certificates for validation.

oauth2client.client.credentials_from_clientsecrets_and_code(*args, **kwargs)[source]

Returns OAuth2Credentials from a clientsecrets file and an auth code.

Will create the right kind of Flow based on the contents of the clientsecrets file or will raise InvalidClientSecretsError for unknown types of Flows.

Parameters:
  • filename – string, File name of clientsecrets.
  • scope – string or iterable of strings, scope(s) to request.
  • code – string, An authorization code, most likely passed down from the client
  • message – string, A friendly string to display to the user if the clientsecrets file is missing or invalid. If message is provided then sys.exit will be called in the case of an error. If message in not provided then clientsecrets.InvalidClientSecretsError will be raised.
  • redirect_uri – string, this is generally set to ‘postmessage’ to match the redirect_uri that the client specified
  • http – httplib2.Http, optional http instance to use to do the fetch
  • cache – An optional cache service client that implements get() and set() methods. See clientsecrets.loadfile() for details.
  • device_uri – string, OAuth 2.0 device authorization endpoint
  • pkce – boolean, default: False, Generate and include a “Proof Key for Code Exchange” (PKCE) with your authorization and token requests. This adds security for installed applications that cannot protect a client_secret. See RFC 7636 for details.
  • code_verifier – bytestring or None, default: None, parameter passed as part of the code exchange when pkce=True. If None, a code_verifier will automatically be generated as part of step1_get_authorize_url(). See RFC 7636 for details.
Returns:

An OAuth2Credentials object.

Raises:
  • FlowExchangeError – if the authorization code cannot be exchanged for an access token
  • UnknownClientSecretsFlowError – if the file describes an unknown kind of Flow.
  • clientsecrets.InvalidClientSecretsError – if the clientsecrets file is invalid.
oauth2client.client.credentials_from_code(*args, **kwargs)[source]

Exchanges an authorization code for an OAuth2Credentials object.

Parameters:
  • client_id – string, client identifier.
  • client_secret – string, client secret.
  • scope – string or iterable of strings, scope(s) to request.
  • code – string, An authorization code, most likely passed down from the client
  • redirect_uri – string, this is generally set to ‘postmessage’ to match the redirect_uri that the client specified
  • http – httplib2.Http, optional http instance to use to do the fetch
  • token_uri – string, URI for token endpoint. For convenience defaults to Google’s endpoints but any OAuth 2.0 provider can be used.
  • auth_uri – string, URI for authorization endpoint. For convenience defaults to Google’s endpoints but any OAuth 2.0 provider can be used.
  • revoke_uri – string, URI for revoke endpoint. For convenience defaults to Google’s endpoints but any OAuth 2.0 provider can be used.
  • device_uri – string, URI for device authorization endpoint. For convenience defaults to Google’s endpoints but any OAuth 2.0 provider can be used.
  • pkce – boolean, default: False, Generate and include a “Proof Key for Code Exchange” (PKCE) with your authorization and token requests. This adds security for installed applications that cannot protect a client_secret. See RFC 7636 for details.
  • code_verifier – bytestring or None, default: None, parameter passed as part of the code exchange when pkce=True. If None, a code_verifier will automatically be generated as part of step1_get_authorize_url(). See RFC 7636 for details.
Returns:

An OAuth2Credentials object.

Raises:
  • FlowExchangeError if the authorization code cannot be exchanged for an
  • access token
oauth2client.client.flow_from_clientsecrets(*args, **kwargs)[source]

Create a Flow from a clientsecrets file.

Will create the right kind of Flow based on the contents of the clientsecrets file or will raise InvalidClientSecretsError for unknown types of Flows.

Parameters:
  • filename – string, File name of client secrets.
  • scope – string or iterable of strings, scope(s) to request.
  • redirect_uri – string, Either the string ‘urn:ietf:wg:oauth:2.0:oob’ for a non-web-based application, or a URI that handles the callback from the authorization server.
  • message – string, A friendly string to display to the user if the clientsecrets file is missing or invalid. If message is provided then sys.exit will be called in the case of an error. If message in not provided then clientsecrets.InvalidClientSecretsError will be raised.
  • cache – An optional cache service client that implements get() and set() methods. See clientsecrets.loadfile() for details.
  • login_hint – string, Either an email address or domain. Passing this hint will either pre-fill the email box on the sign-in form or select the proper multi-login session, thereby simplifying the login flow.
  • device_uri – string, URI for device authorization endpoint. For convenience defaults to Google’s endpoints but any OAuth 2.0 provider can be used.
Returns:

A Flow object.

Raises:
  • UnknownClientSecretsFlowError – if the file describes an unknown kind of Flow.
  • clientsecrets.InvalidClientSecretsError – if the clientsecrets file is invalid.
oauth2client.client.save_to_well_known_file(credentials, well_known_file=None)[source]

Save the provided GoogleCredentials to the well known file.

Parameters:
  • credentials – the credentials to be saved to the well known file; it should be an instance of GoogleCredentials
  • well_known_file – the name of the file where the credentials are to be saved; this parameter is supposed to be used for testing only
oauth2client.client.verify_id_token(*args, **kwargs)[source]

Verifies a signed JWT id_token.

This function requires PyOpenSSL and because of that it does not work on App Engine.

Parameters:
  • id_token – string, A Signed JWT.
  • audience – string, The audience ‘aud’ that the token should be for.
  • http – httplib2.Http, instance to use to make the HTTP request. Callers should supply an instance that has caching enabled.
  • cert_uri – string, URI of the certificates in JSON format to verify the JWT against.
Returns:

The deserialized JSON in the JWT.

Raises:
oauth2client.clientsecrets module

Utilities for reading OAuth 2.0 client secret files.

A client_secrets.json file contains all the information needed to interact with an OAuth 2.0 protected service.

exception oauth2client.clientsecrets.Error[source]

Bases: exceptions.Exception

Base error for this module.

exception oauth2client.clientsecrets.InvalidClientSecretsError[source]

Bases: oauth2client.clientsecrets.Error

Format of ClientSecrets file is invalid.

oauth2client.clientsecrets.load(fp)[source]
oauth2client.clientsecrets.loadfile(filename, cache=None)[source]

Loading of client_secrets JSON file, optionally backed by a cache.

Typical cache storage would be App Engine memcache service, but you can pass in any other cache client that implements these methods:

  • get(key, namespace=ns)
  • set(key, value, namespace=ns)

Usage:

# without caching
client_type, client_info = loadfile('secrets.json')
# using App Engine memcache service
from google.appengine.api import memcache
client_type, client_info = loadfile('secrets.json', cache=memcache)
Parameters:
  • filename – string, Path to a client_secrets.json file on a filesystem.
  • cache – An optional cache service client that implements get() and set()
  • If not specified, the file is always being loaded from (methods.) – a filesystem.
Raises:

InvalidClientSecretsError – In case of a validation error or some I/O failure. Can happen only on cache miss.

Returns:

(client_type, client_info) tuple, as _loadfile() normally would. JSON contents is validated only during first load. Cache hits are not validated.

oauth2client.clientsecrets.loads(s)[source]
oauth2client.crypt module

Crypto-related routines for oauth2client.

exception oauth2client.crypt.AppIdentityError[source]

Bases: exceptions.Exception

Error to indicate crypto failure.

oauth2client.crypt.make_signed_jwt(signer, payload, key_id=None)[source]

Make a signed JWT.

See http://self-issued.info/docs/draft-jones-json-web-token.html.

Parameters:
  • signer – crypt.Signer, Cryptographic signer.
  • payload – dict, Dictionary of data to convert to JSON and then sign.
  • key_id – string, (Optional) Key ID header.
Returns:

string, The JWT for the payload.

oauth2client.crypt.verify_signed_jwt_with_certs(jwt, certs, audience=None)[source]

Verify a JWT against public certs.

See http://self-issued.info/docs/draft-jones-json-web-token.html.

Parameters:
  • jwt – string, A JWT.
  • certs – dict, Dictionary where values of public keys in PEM format.
  • audience – string, The audience, ‘aud’, that this JWT should contain. If None then the JWT’s ‘aud’ parameter is not verified.
Returns:

dict, The deserialized JSON payload in the JWT.

Raises:

AppIdentityError – if any checks are failed.

oauth2client.file module

Utilities for OAuth.

Utilities for making it easier to work with OAuth 2.0 credentials.

class oauth2client.file.Storage(filename)[source]

Bases: oauth2client.client.Storage

Store and retrieve a single credential to and from a file.

locked_delete()[source]

Delete Credentials file.

Parameters:credentials – Credentials, the credentials to store.
locked_get()[source]

Retrieve Credential from file.

Returns:oauth2client.client.Credentials
Raises:IOError if the file is a symbolic link.
locked_put(credentials)[source]

Write Credentials to file.

Parameters:credentials – Credentials, the credentials to store.
Raises:IOError if the file is a symbolic link.
oauth2client.service_account module

oauth2client Service account credentials class.

class oauth2client.service_account.ServiceAccountCredentials(service_account_email, signer, scopes='', private_key_id=None, client_id=None, user_agent=None, token_uri='https://www.googleapis.com/oauth2/v4/token', revoke_uri='https://accounts.google.com/o/oauth2/revoke', **kwargs)[source]

Bases: oauth2client.client.AssertionCredentials

Service Account credential for OAuth 2.0 signed JWT grants.

Supports

  • JSON keyfile (typically contains a PKCS8 key stored as PEM text)
  • .p12 key (stores PKCS12 key and certificate)

Makes an assertion to server using a signed JWT assertion in exchange for an access token.

This credential does not require a flow to instantiate because it represents a two legged flow, and therefore has all of the required information to generate and refresh its own access tokens.

Parameters:
  • service_account_email – string, The email associated with the service account.
  • signercrypt.Signer, A signer which can be used to sign content.
  • scopes – List or string, (Optional) Scopes to use when acquiring an access token.
  • private_key_id – string, (Optional) Private key identifier. Typically only used with a JSON keyfile. Can be sent in the header of a JWT token assertion.
  • client_id – string, (Optional) Client ID for the project that owns the service account.
  • user_agent – string, (Optional) User agent to use when sending request.
  • token_uri – string, URI for token endpoint. For convenience defaults to Google’s endpoints but any OAuth 2.0 provider can be used.
  • revoke_uri – string, URI for revoke endpoint. For convenience defaults to Google’s endpoints but any OAuth 2.0 provider can be used.
  • kwargs – dict, Extra key-value pairs (both strings) to send in the payload body when making an assertion.
MAX_TOKEN_LIFETIME_SECS = 3600

Max lifetime of the token (one hour, in seconds).

NON_SERIALIZED_MEMBERS = frozenset(['_private_key', 'store', '_signer'])

Members that aren’t serialized when object is converted to JSON.

create_delegated(sub)[source]

Create credentials that act as domain-wide delegation of authority.

Use the sub parameter as the subject to delegate on behalf of that user.

For example:

>>> account_sub = 'foo@email.com'
>>> delegate_creds = creds.create_delegated(account_sub)
Parameters:sub – string, An email address that this service account will act on behalf of (via domain-wide delegation).
Returns:ServiceAccountCredentials, a copy of the current service account updated to act on behalf of sub.
create_scoped(scopes)[source]

Create a Credentials object for the given scopes.

The Credentials type is preserved.

create_scoped_required()[source]

Whether this Credentials object is scopeless.

create_scoped(scopes) method needs to be called in order to create a Credentials object for API calls.

create_with_claims(claims)[source]

Create credentials that specify additional claims.

Parameters:claims – dict, key-value pairs for claims.
Returns:ServiceAccountCredentials, a copy of the current service account credentials with updated claims to use when obtaining access tokens.
classmethod from_json(json_data)[source]

Deserialize a JSON-serialized instance.

Inverse to to_json().

Parameters:json_data – dict or string, Serialized JSON (as a string or an already parsed dictionary) representing a credential.
Returns:ServiceAccountCredentials from the serialized data.
classmethod from_json_keyfile_dict(keyfile_dict, scopes='', token_uri=None, revoke_uri=None)[source]

Factory constructor from parsed JSON keyfile.

Parameters:
  • keyfile_dict – dict-like object, The parsed dictionary-like object containing the contents of the JSON keyfile.
  • scopes – List or string, (Optional) Scopes to use when acquiring an access token.
  • token_uri – string, URI for OAuth 2.0 provider token endpoint. If unset and not present in keyfile_dict, defaults to Google’s endpoints.
  • revoke_uri – string, URI for OAuth 2.0 provider revoke endpoint. If unset and not present in keyfile_dict, defaults to Google’s endpoints.
Returns:

ServiceAccountCredentials, a credentials object created from the keyfile.

Raises:
  • ValueError, if the credential type is not SERVICE_ACCOUNT.
  • KeyError, if one of the expected keys is not present in – the keyfile.
classmethod from_json_keyfile_name(filename, scopes='', token_uri=None, revoke_uri=None)[source]

Factory constructor from JSON keyfile by name.

Parameters:
  • filename – string, The location of the keyfile.
  • scopes – List or string, (Optional) Scopes to use when acquiring an access token.
  • token_uri – string, URI for OAuth 2.0 provider token endpoint. If unset and not present in the key file, defaults to Google’s endpoints.
  • revoke_uri – string, URI for OAuth 2.0 provider revoke endpoint. If unset and not present in the key file, defaults to Google’s endpoints.
Returns:

ServiceAccountCredentials, a credentials object created from the keyfile.

Raises:
  • ValueError, if the credential type is not SERVICE_ACCOUNT.
  • KeyError, if one of the expected keys is not present in – the keyfile.
classmethod from_p12_keyfile(service_account_email, filename, private_key_password=None, scopes='', token_uri='https://www.googleapis.com/oauth2/v4/token', revoke_uri='https://accounts.google.com/o/oauth2/revoke')[source]

Factory constructor from JSON keyfile.

Parameters:
  • service_account_email – string, The email associated with the service account.
  • filename – string, The location of the PKCS#12 keyfile.
  • private_key_password – string, (Optional) Password for PKCS#12 private key. Defaults to notasecret.
  • scopes – List or string, (Optional) Scopes to use when acquiring an access token.
  • token_uri – string, URI for token endpoint. For convenience defaults to Google’s endpoints but any OAuth 2.0 provider can be used.
  • revoke_uri – string, URI for revoke endpoint. For convenience defaults to Google’s endpoints but any OAuth 2.0 provider can be used.
Returns:

ServiceAccountCredentials, a credentials object created from the keyfile.

Raises:
  • NotImplementedError if pyOpenSSL is not installed / not the
  • active crypto library.
classmethod from_p12_keyfile_buffer(service_account_email, file_buffer, private_key_password=None, scopes='', token_uri='https://www.googleapis.com/oauth2/v4/token', revoke_uri='https://accounts.google.com/o/oauth2/revoke')[source]

Factory constructor from JSON keyfile.

Parameters:
  • service_account_email – string, The email associated with the service account.
  • file_buffer – stream, A buffer that implements read() and contains the PKCS#12 key contents.
  • private_key_password – string, (Optional) Password for PKCS#12 private key. Defaults to notasecret.
  • scopes – List or string, (Optional) Scopes to use when acquiring an access token.
  • token_uri – string, URI for token endpoint. For convenience defaults to Google’s endpoints but any OAuth 2.0 provider can be used.
  • revoke_uri – string, URI for revoke endpoint. For convenience defaults to Google’s endpoints but any OAuth 2.0 provider can be used.
Returns:

ServiceAccountCredentials, a credentials object created from the keyfile.

Raises:
  • NotImplementedError if pyOpenSSL is not installed / not the
  • active crypto library.
serialization_data
service_account_email

Get the email for the current service account.

Returns:string, The email associated with the service account.
sign_blob(blob)[source]

Cryptographically sign a blob (of bytes).

Implements abstract method oauth2client.client.AssertionCredentials.sign_blob().

Parameters:blob – bytes, Message to be signed.
Returns:tuple, A pair of the private key ID used to sign the blob and the signed contents.
oauth2client.tools module

Command-line tools for authenticating via OAuth 2.0

Do the OAuth 2.0 Web Server dance for a command line application. Stores the generated credentials in a common file that is used by other example apps in the same directory.

oauth2client.tools.run_flow(*args, **kwargs)[source]

Core code for a command-line application.

The run() function is called from your application and runs through all the steps to obtain 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.

It presumes it is run from a command-line application and supports the following flags:

--auth_host_name (string, default: localhost)
Host name to use when running a local web server to handle redirects during OAuth authorization.
--auth_host_port (integer, default: [8080, 8090])
Port to use when running a local web server to handle redirects during OAuth authorization. Repeat this option to specify a list of values.
--[no]auth_local_webserver (boolean, default: True)
Run a local web server to handle redirects during OAuth authorization.

The tools module defines an ArgumentParser the already contains the flag definitions that run() requires. You can pass that ArgumentParser to your ArgumentParser constructor:

parser = argparse.ArgumentParser(
    description=__doc__,
    formatter_class=argparse.RawDescriptionHelpFormatter,
    parents=[tools.argparser])
flags = parser.parse_args(argv)
Parameters:
  • flow – Flow, an OAuth 2.0 Flow to step through.
  • storage – Storage, a Storage to store the credential in.
  • flagsargparse.Namespace, (Optional) The command-line flags. This is the object returned from calling parse_args() on argparse.ArgumentParser as described above. Defaults to argparser.parse_args().
  • http – An instance of httplib2.Http.request or something that acts like it.
Returns:

Credentials, the obtained credential.

oauth2client.tools.message_if_missing(filename)[source]

Helpful message to display if the CLIENT_SECRETS file is missing.

oauth2client.transport module
class oauth2client.transport.MemoryCache[source]

Bases: object

httplib2 Cache implementation which only caches locally.

delete(key)[source]
get(key)[source]
set(key, value)[source]
oauth2client.transport.clean_headers(headers)[source]

Forces header keys and values to be strings, i.e not unicode.

The httplib module just concats the header keys and values in a way that may make the message header a unicode string, which, if it then tries to contatenate to a binary request body may result in a unicode decode error.

Parameters:headers – dict, A dictionary of headers.
Returns:The same dictionary but with all the keys converted to strings.
oauth2client.transport.get_cached_http()[source]

Return an HTTP object which caches results returned.

This is intended to be used in methods like oauth2client.client.verify_id_token(), which calls to the same URI to retrieve certs.

Returns:httplib2.Http, an HTTP object with a MemoryCache
oauth2client.transport.get_http_object(*args, **kwargs)[source]

Return a new HTTP object.

Parameters:
  • *args – tuple, The positional arguments to be passed when contructing a new HTTP object.
  • **kwargs – dict, The keyword arguments to be passed when contructing a new HTTP object.
Returns:

httplib2.Http, an HTTP object.

oauth2client.transport.request(http, uri, method='GET', body=None, headers=None, redirections=5, connection_type=None)[source]

Make an HTTP request with an HTTP object and arguments.

Parameters:
  • http – httplib2.Http, an http object to be used to make requests.
  • uri – string, The URI to be requested.
  • method – string, The HTTP method to use for the request. Defaults to ‘GET’.
  • body – string, The payload / body in HTTP request. By default there is no payload.
  • headers – dict, Key-value pairs of request headers. By default there are no headers.
  • redirections – int, The number of allowed 203 redirects for the request. Defaults to 5.
  • connection_type – httplib.HTTPConnection, a subclass to be used for establishing connection. If not set, the type will be determined from the uri.
Returns:

tuple, a pair of a httplib2.Response with the status code and other headers and the bytes of the content returned.

oauth2client.transport.wrap_http_for_auth(credentials, http)[source]

Prepares an HTTP object’s request method for auth.

Wraps HTTP requests with logic to catch auth failures (typically identified via a 401 status code). In the event of failure, tries to refresh the token used and then retry the original request.

Parameters:
  • credentials – Credentials, the credentials used to identify the authenticated user.
  • http – httplib2.Http, an http object to be used to make auth requests.
oauth2client.transport.wrap_http_for_jwt_access(credentials, http)[source]

Prepares an HTTP object’s request method for JWT access.

Wraps HTTP requests with logic to catch auth failures (typically identified via a 401 status code). In the event of failure, tries to refresh the token used and then retry the original request.

Parameters:
  • credentials – _JWTAccessCredentials, the credentials used to identify a service account that uses JWT access tokens.
  • http – httplib2.Http, an http object to be used to make auth requests.

Module contents

Client library for using OAuth2, especially with Google APIs.

Supported Python Versions

We support Python 2.7 and 3.4+. (Whatever this file says, the truth is always represented by our tox.ini).

We explicitly decided to support Python 3 beginning with version 3.4. Reasons for this include:

  • Encouraging use of newest versions of Python 3
  • Following the lead of prominent open-source projects
  • Unicode literal support which allows for a cleaner codebase that works in both Python 2 and Python 3
  • Prominent projects like django have dropped support for earlier versions (3.3 support dropped in December 2015, and 2.6 support dropped in September 2014)