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: