As of January 1, 2020 this library no longer supports Python 2 on the latest released version. Library versions released prior to that date will continue to be available. For more information please visit Python 2 support on Google Cloud.

google_auth_oauthlib.flow module

OAuth 2.0 Authorization Flow

This module provides integration with requests-oauthlib for running the OAuth 2.0 Authorization Flow and acquiring user credentials. See Using OAuth 2.0 to Access Google APIs for an overview of OAuth 2.0 authorization scenarios Google APIs support.

Here’s an example of using InstalledAppFlow:

from google_auth_oauthlib.flow import InstalledAppFlow

# Create the flow using the client secrets file from the Google API
# Console.
flow = InstalledAppFlow.from_client_secrets_file(
    'client_secrets.json',
    scopes=['profile', 'email'])

flow.run_local_server()

# You can use flow.credentials, or you can just get a requests session
# using flow.authorized_session.
session = flow.authorized_session()

profile_info = session.get(
    'https://www.googleapis.com/userinfo/v2/me').json()

print(profile_info)
# {'name': '...',  'email': '...', ...}
class google_auth_oauthlib.flow.Flow(oauth2session, client_type, client_config, redirect_uri=None, code_verifier=None, autogenerate_code_verifier=True)[source]

Bases: object

OAuth 2.0 Authorization Flow

This class uses a requests_oauthlib.OAuth2Session instance at oauth2session to perform all of the OAuth 2.0 logic. This class just provides convenience methods and sane defaults for doing Google’s particular flavors of OAuth 2.0.

Typically you’ll construct an instance of this flow using from_client_secrets_file() and a client secrets file obtained from the Google API Console.

Parameters
  • oauth2session (requests_oauthlib.OAuth2Session) – The OAuth 2.0 session from requests-oauthlib.

  • client_type (str) – The client type, either web or installed.

  • client_config (Mapping[str, Any]) – The client configuration in the Google client secrets format.

  • redirect_uri (str) – The OAuth 2.0 redirect URI if known at flow creation time. Otherwise, it will need to be set using redirect_uri.

  • code_verifier (str) – random string of 43-128 chars used to verify the key exchange.using PKCE.

  • autogenerate_code_verifier (bool) – If true, auto-generate a code_verifier.

authorization_url(**kwargs)[source]

Generates an authorization URL.

This is the first step in the OAuth 2.0 Authorization Flow. The user’s browser should be redirected to the returned URL.

This method calls requests_oauthlib.OAuth2Session.authorization_url() and specifies the client configuration’s authorization URI (usually Google’s authorization server) and specifies that “offline” access is desired. This is required in order to obtain a refresh token.

Parameters

kwargs – Additional arguments passed through to requests_oauthlib.OAuth2Session.authorization_url()

Returns

The generated authorization URL and state. The

user must visit the URL to complete the flow. The state is used when completing the flow to verify that the request originated from your application. If your application is using a different Flow instance to obtain the token, you will need to specify the state when constructing the Flow.

Return type

Tuple[str, str]

authorized_session()[source]

Returns a requests.Session authorized with credentials.

fetch_token() must be called before this method. This method constructs a google.auth.transport.requests.AuthorizedSession class using this flow’s credentials.

Returns

The constructed

session.

Return type

google.auth.transport.requests.AuthorizedSession

client_config

The OAuth 2.0 client configuration.

Type

Mapping[str, Any]

client_type

The client type, either 'web' or 'installed'

Type

str

property credentials

Returns credentials from the OAuth 2.0 session.

fetch_token() must be called before accessing this. This method constructs a google.oauth2.credentials.Credentials class using the session’s token and the client config.

Returns

The constructed credentials.

Return type

google.oauth2.credentials.Credentials

Raises

ValueError – If there is no access token in the session.

fetch_token(**kwargs)[source]

Completes the Authorization Flow and obtains an access token.

This is the final step in the OAuth 2.0 Authorization Flow. This is called after the user consents.

This method calls requests_oauthlib.OAuth2Session.fetch_token() and specifies the client configuration’s token URI (usually Google’s token server).

Parameters

kwargs – Arguments passed through to requests_oauthlib.OAuth2Session.fetch_token(). At least one of code or authorization_response must be specified.

Returns

The obtained tokens. Typically, you will not use

return value of this function and instead use credentials() to obtain a Credentials instance.

Return type

Mapping[str, str]

classmethod from_client_config(client_config, scopes, **kwargs)[source]

Creates a requests_oauthlib.OAuth2Session from client configuration loaded from a Google-format client secrets file.

Parameters
  • client_config (Mapping[str, Any]) – The client configuration in the Google client secrets format.

  • scopes (Sequence[str]) – The list of scopes to request during the flow.

  • kwargs – Any additional parameters passed to requests_oauthlib.OAuth2Session

Returns

The constructed Flow instance.

Return type

Flow

Raises

ValueError – If the client configuration is not in the correct format.

classmethod from_client_secrets_file(client_secrets_file, scopes, **kwargs)[source]

Creates a Flow instance from a Google client secrets file.

Parameters
  • client_secrets_file (str) – The path to the client secrets .json file.

  • scopes (Sequence[str]) – The list of scopes to request during the flow.

  • kwargs – Any additional parameters passed to requests_oauthlib.OAuth2Session

Returns

The constructed Flow instance.

Return type

Flow

oauth2session

The OAuth 2.0 session.

Type

requests_oauthlib.OAuth2Session

property redirect_uri

The OAuth 2.0 redirect URI. Pass-through to self.oauth2session.redirect_uri.

class google_auth_oauthlib.flow.InstalledAppFlow(oauth2session, client_type, client_config, redirect_uri=None, code_verifier=None, autogenerate_code_verifier=True)[source]

Bases: google_auth_oauthlib.flow.Flow

Authorization flow helper for installed applications.

This Flow subclass makes it easier to perform the Installed Application Authorization Flow. This flow is useful for local development or applications that are installed on a desktop operating system.

This flow uses a local server strategy provided by run_local_server().

Example:

from google_auth_oauthlib.flow import InstalledAppFlow

flow = InstalledAppFlow.from_client_secrets_file(
    'client_secrets.json',
    scopes=['profile', 'email'])

flow.run_local_server()

session = flow.authorized_session()

profile_info = session.get(
    'https://www.googleapis.com/userinfo/v2/me').json()

print(profile_info)
# {'name': '...',  'email': '...', ...}

Note that this isn’t the only way to accomplish the installed application flow, just one of the most common. You can use the Flow class to perform the same flow with different methods of presenting the authorization URL to the user or obtaining the authorization response, such as using an embedded web view.

Parameters
  • oauth2session (requests_oauthlib.OAuth2Session) – The OAuth 2.0 session from requests-oauthlib.

  • client_type (str) – The client type, either web or installed.

  • client_config (Mapping[str, Any]) – The client configuration in the Google client secrets format.

  • redirect_uri (str) – The OAuth 2.0 redirect URI if known at flow creation time. Otherwise, it will need to be set using redirect_uri.

  • code_verifier (str) – random string of 43-128 chars used to verify the key exchange.using PKCE.

  • autogenerate_code_verifier (bool) – If true, auto-generate a code_verifier.

authorization_url(**kwargs)

Generates an authorization URL.

This is the first step in the OAuth 2.0 Authorization Flow. The user’s browser should be redirected to the returned URL.

This method calls requests_oauthlib.OAuth2Session.authorization_url() and specifies the client configuration’s authorization URI (usually Google’s authorization server) and specifies that “offline” access is desired. This is required in order to obtain a refresh token.

Parameters

kwargs – Additional arguments passed through to requests_oauthlib.OAuth2Session.authorization_url()

Returns

The generated authorization URL and state. The

user must visit the URL to complete the flow. The state is used when completing the flow to verify that the request originated from your application. If your application is using a different Flow instance to obtain the token, you will need to specify the state when constructing the Flow.

Return type

Tuple[str, str]

authorized_session()

Returns a requests.Session authorized with credentials.

fetch_token() must be called before this method. This method constructs a google.auth.transport.requests.AuthorizedSession class using this flow’s credentials.

Returns

The constructed

session.

Return type

google.auth.transport.requests.AuthorizedSession

client_config

The OAuth 2.0 client configuration.

Type

Mapping[str, Any]

client_type

The client type, either 'web' or 'installed'

Type

str

property credentials

Returns credentials from the OAuth 2.0 session.

fetch_token() must be called before accessing this. This method constructs a google.oauth2.credentials.Credentials class using the session’s token and the client config.

Returns

The constructed credentials.

Return type

google.oauth2.credentials.Credentials

Raises

ValueError – If there is no access token in the session.

fetch_token(**kwargs)

Completes the Authorization Flow and obtains an access token.

This is the final step in the OAuth 2.0 Authorization Flow. This is called after the user consents.

This method calls requests_oauthlib.OAuth2Session.fetch_token() and specifies the client configuration’s token URI (usually Google’s token server).

Parameters

kwargs – Arguments passed through to requests_oauthlib.OAuth2Session.fetch_token(). At least one of code or authorization_response must be specified.

Returns

The obtained tokens. Typically, you will not use

return value of this function and instead use credentials() to obtain a Credentials instance.

Return type

Mapping[str, str]

classmethod from_client_config(client_config, scopes, **kwargs)

Creates a requests_oauthlib.OAuth2Session from client configuration loaded from a Google-format client secrets file.

Parameters
  • client_config (Mapping[str, Any]) – The client configuration in the Google client secrets format.

  • scopes (Sequence[str]) – The list of scopes to request during the flow.

  • kwargs – Any additional parameters passed to requests_oauthlib.OAuth2Session

Returns

The constructed Flow instance.

Return type

Flow

Raises

ValueError – If the client configuration is not in the correct format.

classmethod from_client_secrets_file(client_secrets_file, scopes, **kwargs)

Creates a Flow instance from a Google client secrets file.

Parameters
  • client_secrets_file (str) – The path to the client secrets .json file.

  • scopes (Sequence[str]) – The list of scopes to request during the flow.

  • kwargs – Any additional parameters passed to requests_oauthlib.OAuth2Session

Returns

The constructed Flow instance.

Return type

Flow

oauth2session

The OAuth 2.0 session.

Type

requests_oauthlib.OAuth2Session

property redirect_uri

The OAuth 2.0 redirect URI. Pass-through to self.oauth2session.redirect_uri.

run_local_server(host='localhost', bind_addr=None, port=8080, authorization_prompt_message='Please visit this URL to authorize this application: {url}', success_message='The authentication flow has completed. You may close this window.', open_browser=True, redirect_uri_trailing_slash=True, timeout_seconds=None, token_audience=None, browser=None, **kwargs)[source]

Run the flow using the server strategy.

The server strategy instructs the user to open the authorization URL in their browser and will attempt to automatically open the URL for them. It will start a local web server to listen for the authorization response. Once authorization is complete the authorization server will redirect the user’s browser to the local web server. The web server will get the authorization code from the response and shutdown. The code is then exchanged for a token.

Parameters
  • host (str) – The hostname for the local redirect server. This will be served over http, not https.

  • bind_addr (str) – Optionally provide an ip address for the redirect server to listen on when it is not the same as host (e.g. in a container). Default value is None, which means that the redirect server will listen on the ip address specified in the host parameter.

  • port (int) – The port for the local redirect server.

  • authorization_prompt_message (str | None) – The message to display to tell the user to navigate to the authorization URL. If None or empty, don’t display anything.

  • success_message (str) – The message to display in the web browser the authorization flow is complete.

  • open_browser (bool) – Whether or not to open the authorization URL in the user’s browser.

  • redirect_uri_trailing_slash (bool) – whether or not to add trailing slash when constructing the redirect_uri. Default value is True.

  • timeout_seconds (int) – It will raise an error after the timeout timing if there are no credentials response. The value is in seconds. When set to None there is no timeout. Default value is None.

  • token_audience (str) – Passed along with the request for an access token. Determines the endpoints with which the token can be used. Optional.

  • browser (str) – specify which browser to open for authentication. If not specified this defaults to default browser.

  • kwargs – Additional keyword arguments passed through to authorization_url().

Returns

The OAuth 2.0 credentials

for the user.

Return type

google.oauth2.credentials.Credentials