google_auth_oauthlib.flow module — google-auth-oauthlib 0.4.1 documentation (original) (raw)

OAuth 2.0 Authorization Flow

This module provides integration with requests-oauthlib for running theOAuth 2.0 Authorization Flow and acquiring user credentials.

Here’s an example of using Flow with the installed application authorization flow:

from google_auth_oauthlib.flow import Flow

Create the flow using the client secrets file from the Google API

Console.

flow = Flow.from_client_secrets_file( 'path/to/client_secrets.json', scopes=['profile', 'email'], redirect_uri='urn:ietf:wg:oauth:2.0:oob')

Tell the user to go to the authorization URL.

auth_url, _ = flow.authorization_url(prompt='consent')

print('Please go to this URL: {}'.format(auth_url))

The user will get an authorization code. This code is used to get the

access token.

code = input('Enter the authorization code: ') flow.fetch_token(code=code)

You can use flow.credentials, or you can just get a requests session

using flow.authorized_session.

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

This particular flow can be handled entirely by usingInstalledAppFlow.

class Flow(oauth2session, client_type, client_config, redirect_uri=None, code_verifier=None, autogenerate_code_verifier=False)[source]

Bases: object

OAuth 2.0 Authorization Flow

This class uses a requests_oauthlib.OAuth2Session instance atoauth2session 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 usingfrom_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 orinstalled. 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 usingredirect_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.

client_type = None

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

Type: str

client_config = None

The OAuth 2.0 client configuration.

Type: Mapping [ str, Any ]

oauth2session = None

The OAuth 2.0 session.

Type: requests_oauthlib.OAuth2Session

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. kwargsAny additional parameters passed torequests_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. kwargsAny additional parameters passed torequests_oauthlib.OAuth2Session
Returns: The constructed Flow instance.
Return type: Flow

redirect_uri

The OAuth 2.0 redirect URI. Pass-through toself.oauth2session.redirect_uri.

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 callsrequests_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 torequests_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 differentFlow instance to obtain the token, you will need to specify the state when constructing the Flow.
Return type: Tuple [ str, str ]

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 callsrequests_oauthlib.OAuth2Session.fetch_token()and specifies the client configuration’s token URI (usually Google’s token server).

Parameters: kwargs – Arguments passed through torequests_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 and usecredentials() to obtain aCredentials instance.
Return type: Mapping [ str, str ]

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.

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.AuthorizedSessionclass using this flow’s credentials.

Returns: The constructed session.
Return type: google.auth.transport.requests.AuthorizedSession

class InstalledAppFlow(oauth2session, client_type, client_config, redirect_uri=None, code_verifier=None, autogenerate_code_verifier=False)[source]

Bases: google_auth_oauthlib.flow.Flow

Authorization flow helper for installed applications.

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

This flow has two strategies: The console strategy provided byrun_console() and the local server strategy provided byrun_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 these aren’t the only two ways to accomplish the installed application flow, they are just the most common ways. You can use theFlow 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 orinstalled. 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 usingredirect_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.

run_console(authorization_prompt_message='Please visit this URL to authorize this application: {url}', authorization_code_message='Enter the authorization code: ', **kwargs)[source]

Run the flow using the console strategy.

The console strategy instructs the user to open the authorization URL in their browser. Once the authorization is complete the authorization server will give the user a code. The user then must copy & paste this code into the application. The code is then exchanged for a token.

Parameters: authorization_prompt_message (str) – The message to display to tell the user to navigate to the authorization URL. authorization_code_message (str) – The message to display when prompting the user for the authorization code. kwargs – Additional keyword arguments passed through toauthorization_url().
Returns: The OAuth 2.0 credentials for the user.
Return type: google.oauth2.credentials.Credentials

run_local_server(host='localhost', 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, **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. port (int) – The port for the local redirect server. authorization_prompt_message (str) – The message to display to tell the user to navigate to the authorization URL. 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. kwargs – Additional keyword arguments passed through toauthorization_url().
Returns: The OAuth 2.0 credentials for the user.
Return type: google.oauth2.credentials.Credentials

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 callsrequests_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 torequests_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 differentFlow 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.AuthorizedSessionclass using this flow’s credentials.

Returns: The constructed session.
Return type: google.auth.transport.requests.AuthorizedSession

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 callsrequests_oauthlib.OAuth2Session.fetch_token()and specifies the client configuration’s token URI (usually Google’s token server).

Parameters: kwargs – Arguments passed through torequests_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 and usecredentials() to obtain aCredentials 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. kwargsAny additional parameters passed torequests_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. kwargsAny additional parameters passed torequests_oauthlib.OAuth2Session
Returns: The constructed Flow instance.
Return type: Flow

redirect_uri

The OAuth 2.0 redirect URI. Pass-through toself.oauth2session.redirect_uri.