Package oauth2client :: Module client
[hide private]
[frames] | no frames]

Module client

source code

An OAuth 2.0 client.

Tools for interacting with OAuth 2.0 protected resources.


Author: jcgregorio@google.com (Joe Gregorio)

Classes [hide private]
  Error
Base error for this module.
  FlowExchangeError
Error trying to exchange an authorization grant for an access token.
  AccessTokenRefreshError
Error trying to refresh an expired access token.
  TokenRevokeError
Error trying to revoke a token.
  UnknownClientSecretsFlowError
The client secrets file called for an unknown type of OAuth 2.0 flow.
  AccessTokenCredentialsError
Having only the access_token means no refresh is possible.
  VerifyJwtTokenError
Could not retrieve certificates for validation.
  NonAsciiHeaderError
Header names and values must be ASCII strings.
  ApplicationDefaultCredentialsError
Error retrieving the Application Default Credentials.
  OAuth2DeviceCodeError
Error trying to retrieve a device code.
  CryptoUnavailableError
Raised when a crypto library is required, but none is available.
  MemoryCache
httplib2 Cache implementation which only caches locally.
  Credentials
Base class for all Credentials objects.
  Flow
Base class for all Flow objects.
  Storage
Base class for all Storage objects.
  OAuth2Credentials
Credentials object for OAuth 2.0.
  AccessTokenCredentials
Credentials object for OAuth 2.0.
  GoogleCredentials
Application Default Credentials for use in calling Google APIs.
  AssertionCredentials
Abstract Credentials object used for OAuth 2.0 assertion grants.
  SignedJwtAssertionCredentials
Credentials object used for OAuth 2.0 Signed JWT assertion grants.
  DeviceFlowInfo
Intermediate information the OAuth2 for devices flow.
  OAuth2WebServerFlow
Does the Web Server Flow for OAuth 2.0.
Functions [hide private]
 
_abstract() source code
 
clean_headers(headers)
Forces header keys and values to be strings, i.e not unicode.
source code
 
_update_query_params(uri, params)
Updates a URI with new query parameters.
source code
 
_get_environment(urlopen=None)
Detect the environment the code is being run on.
source code
 
save_to_well_known_file(credentials, well_known_file=None)
Save the provided GoogleCredentials to the well known file.
source code
 
_get_environment_variable_file() source code
 
_get_well_known_file()
Get the well known file produced by command 'gcloud auth login'.
source code
 
_get_application_default_credential_from_file(application_default_credential_filename)
Build the Application Default Credentials from file.
source code
 
_raise_exception_for_missing_fields(missing_fields) source code
 
_raise_exception_for_reading_json(credential_file, extra_help, error) source code
 
_get_application_default_credential_GAE() source code
 
_get_application_default_credential_GCE() source code
 
_RequireCryptoOrDie()
Ensure we have a crypto library, or throw CryptoUnavailableError.
source code
 
verify_id_token(id_token, audience, http=None, cert_uri=ID_TOKEN_VERIFICATION_CERTS)
Verifies a signed JWT id_token.
source code
 
_urlsafe_b64decode(b64string) source code
 
_extract_id_token(id_token)
Extract the JSON payload from a JWT.
source code
 
_parse_exchange_token_response(content)
Parses response of an exchange token request.
source code
 
credentials_from_code(client_id, client_secret, scope, code, redirect_uri='postmessage', http=None, user_agent=None, token_uri=GOOGLE_TOKEN_URI, auth_uri=GOOGLE_AUTH_URI, revoke_uri=GOOGLE_REVOKE_URI, device_uri=GOOGLE_DEVICE_URI)
Exchanges an authorization code for an OAuth2Credentials object.
source code
 
credentials_from_clientsecrets_and_code(filename, scope, code, message=None, redirect_uri='postmessage', http=None, cache=None, device_uri=None)
Returns OAuth2Credentials from a clientsecrets file and an auth code.
source code
 
flow_from_clientsecrets(filename, scope, redirect_uri=None, message=None, cache=None, login_hint=None, device_uri=None)
Create a Flow from a clientsecrets file.
source code
Variables [hide private]
  HAS_CRYPTO = True
  HAS_OPENSSL = True
  logger = logging.getLogger(__name__)
  EXPIRY_FORMAT = '%Y-%m-%dT%H:%M:%SZ'
  ID_TOKEN_VERIFICATION_CERTS = 'https://www.googleapis.com/oaut...
  ID_TOKEN_VERIFICATON_CERTS = 'https://www.googleapis.com/oauth...
  OOB_CALLBACK_URN = 'urn:ietf:wg:oauth:2.0:oob'
  REFRESH_STATUS_CODES = [401]
  AUTHORIZED_USER = 'authorized_user'
  SERVICE_ACCOUNT = 'service_account'
  GOOGLE_APPLICATION_CREDENTIALS = 'GOOGLE_APPLICATION_CREDENTIALS'
  ADC_HELP_MSG = 'The Application Default Credentials are not av...
  AccessTokenInfo = collections.namedtuple('AccessTokenInfo', ['...
  _env_name = None
  _cached_http = httplib2.Http(MemoryCache())
Function Details [hide private]

clean_headers(headers)

source code 
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.

Args:
  headers: dict, A dictionary of headers.

Returns:
  The same dictionary but with all the keys converted to strings.

_update_query_params(uri, params)

source code 
Updates a URI with new query parameters.

Args:
  uri: string, A valid URI, with potential existing query parameters.
  params: dict, A dictionary of query parameters.

Returns:
  The same URI but with the new query parameters added.

save_to_well_known_file(credentials, well_known_file=None)

source code 
Save the provided GoogleCredentials to the well known file.

Args:
  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

_RequireCryptoOrDie()

source code 
Ensure we have a crypto library, or throw CryptoUnavailableError.

The oauth2client.crypt module requires either PyCrypto or PyOpenSSL
to be available in order to function, but these are optional
dependencies.

verify_id_token(id_token, audience, http=None, cert_uri=ID_TOKEN_VERIFICATION_CERTS)

source code 
Verifies a signed JWT id_token.

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

Args:
  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.crypt.AppIdentityError: if the JWT fails to verify.
  CryptoUnavailableError: if no crypto library is available.

Decorators:
  • @util.positional(2)

_extract_id_token(id_token)

source code 
Extract the JSON payload from a JWT.

Does the extraction w/o checking the signature.

Args:
  id_token: string, OAuth 2.0 id_token.

Returns:
  object, The deserialized JSON payload.

_parse_exchange_token_response(content)

source code 
Parses response of an exchange token request.

Most providers return JSON but some (e.g. Facebook) return a
url-encoded string.

Args:
  content: The body of a response

Returns:
  Content as a dictionary object. Note that the dict could be empty,
  i.e. {}. That basically indicates a failure.

credentials_from_code(client_id, client_secret, scope, code, redirect_uri='postmessage', http=None, user_agent=None, token_uri=GOOGLE_TOKEN_URI, auth_uri=GOOGLE_AUTH_URI, revoke_uri=GOOGLE_REVOKE_URI, device_uri=GOOGLE_DEVICE_URI)

source code 
Exchanges an authorization code for an OAuth2Credentials object.

Args:
  client_id: string, client identifier.
  client_secret: string, client secret.
  scope: string or iterable of strings, scope(s) to request.
  code: string, An authroization 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.

Returns:
  An OAuth2Credentials object.

Raises:
  FlowExchangeError if the authorization code cannot be exchanged for an
   access token

Decorators:
  • @util.positional(4)

credentials_from_clientsecrets_and_code(filename, scope, code, message=None, redirect_uri='postmessage', http=None, cache=None, device_uri=None)

source code 
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.

Args:
  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

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.

Decorators:
  • @util.positional(3)

flow_from_clientsecrets(filename, scope, redirect_uri=None, message=None, cache=None, login_hint=None, device_uri=None)

source code 
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.

Args:
  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.

Decorators:
  • @util.positional(2)

Variables Details [hide private]

ID_TOKEN_VERIFICATION_CERTS

Value:
'https://www.googleapis.com/oauth2/v1/certs'

ID_TOKEN_VERIFICATON_CERTS

Value:
'https://www.googleapis.com/oauth2/v1/certs'

ADC_HELP_MSG

Value:
'The Application Default Credentials are not available. They are avail\
able ' 'if running in Google Compute Engine. Otherwise, the environmen\
t variable '+ GOOGLE_APPLICATION_CREDENTIALS+ ' must be defined pointi\
ng to a file defining the credentials. See ' 'https://developers.googl\
e.com/accounts/docs/application-default-credentials' ' for more inform\
ation.'

AccessTokenInfo

Value:
collections.namedtuple('AccessTokenInfo', ['access_token', 'expires_in\
'])