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=False)[source]¶
Bases:
objectOAuth 2.0 Authorization Flow
This class uses a
requests_oauthlib.OAuth2Sessioninstance atoauth2sessionto 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
weborinstalled.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
Flowinstance to obtain the token, you will need to specify thestatewhen constructing theFlow.
- Return type
- authorized_session()[source]¶
Returns a
requests.Sessionauthorized with credentials.fetch_token()must be called before this method. This method constructs agoogle.auth.transport.requests.AuthorizedSessionclass using this flow’scredentials.- Returns
- The constructed
session.
- Return type
- property credentials¶
Returns credentials from the OAuth 2.0 session.
fetch_token()must be called before accessing this. This method constructs agoogle.oauth2.credentials.Credentialsclass using the session’s token and the client config.- Returns
The constructed credentials.
- Return type
- 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 ofcodeorauthorization_responsemust be specified.- Returns
- The obtained tokens. Typically, you will not use
return value of this function and instead and use
credentials()to obtain aCredentialsinstance.
- Return type
- classmethod from_client_config(client_config, scopes, **kwargs)[source]¶
Creates a
requests_oauthlib.OAuth2Sessionfrom 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
- 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
Flowinstance from a Google client secrets file.
- 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=False)[source]¶
Bases:
google_auth_oauthlib.flow.FlowAuthorization flow helper for installed applications.
This
Flowsubclass 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
Flowclass 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
weborinstalled.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
Flowinstance to obtain the token, you will need to specify thestatewhen constructing theFlow.
- Return type
- authorized_session()¶
Returns a
requests.Sessionauthorized with credentials.fetch_token()must be called before this method. This method constructs agoogle.auth.transport.requests.AuthorizedSessionclass using this flow’scredentials.- Returns
- The constructed
session.
- Return type
- property credentials¶
Returns credentials from the OAuth 2.0 session.
fetch_token()must be called before accessing this. This method constructs agoogle.oauth2.credentials.Credentialsclass using the session’s token and the client config.- Returns
The constructed credentials.
- Return type
- 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 ofcodeorauthorization_responsemust be specified.- Returns
- The obtained tokens. Typically, you will not use
return value of this function and instead and use
credentials()to obtain aCredentialsinstance.
- Return type
- classmethod from_client_config(client_config, scopes, **kwargs)¶
Creates a
requests_oauthlib.OAuth2Sessionfrom 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
- Raises
ValueError – If the client configuration is not in the correct format.
- classmethod from_client_secrets_file(client_secrets_file, scopes, **kwargs)¶
Creates a
Flowinstance from a Google client secrets file.
- 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_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.
Deprecated since version 0.5.0: Use
run_local_server()instead.The OAuth out-of-band (OOB) flow is deprecated. New clients will be unable to use this flow starting on Feb 28, 2022. This flow will be deprecated for all clients on Oct 3, 2022. Migrate to an alternative flow.
See https://developers.googleblog.com/2022/02/making-oauth-flows-safer.html?m=1#disallowed-oob”
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 to
authorization_url().
- Returns
- The OAuth 2.0 credentials
for the user.
- Return type
- 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, redirect_uri_trailing_slash=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.
redirect_uri_trailing_slash (bool) – whether or not to add trailing slash when constructing the redirect_uri. Default value is True.
kwargs – Additional keyword arguments passed through to
authorization_url().
- Returns
- The OAuth 2.0 credentials
for the user.
- Return type