Google Authentication Library - oauthlib integration for OAuth 2.0 flows.
83
Low-level integration utilities for working with requests-oauthlib sessions and converting between different credential formats. These functions provide the foundation for higher-level OAuth flows.
Create OAuth 2.0 sessions from Google client configuration formats.
def session_from_client_config(
client_config: Mapping[str, Any],
scopes: Sequence[str],
**kwargs
) -> Tuple[requests_oauthlib.OAuth2Session, Mapping[str, Any]]:
"""
Create OAuth2Session from client configuration dictionary.
Args:
client_config: Client configuration in Google client secrets format
scopes: List of OAuth 2.0 scopes to request
**kwargs: Additional parameters passed to OAuth2Session
Returns:
Tuple of (OAuth2Session instance, validated client config)
Raises:
ValueError: If client configuration is not in correct format
"""
def session_from_client_secrets_file(
client_secrets_file: str,
scopes: Sequence[str],
**kwargs
) -> Tuple[requests_oauthlib.OAuth2Session, Mapping[str, Any]]:
"""
Create OAuth2Session from client secrets JSON file.
Args:
client_secrets_file: Path to client secrets .json file
scopes: List of OAuth 2.0 scopes to request
**kwargs: Additional parameters passed to OAuth2Session
Returns:
Tuple of (OAuth2Session instance, validated client config)
"""Convert between requests-oauthlib sessions and google-auth credentials objects.
def credentials_from_session(
session: requests_oauthlib.OAuth2Session,
client_config: Optional[Mapping[str, Any]] = None
) -> google.oauth2.credentials.Credentials:
"""
Create Google Auth credentials from OAuth2Session.
Must call fetch_token() on session before using this function.
Converts session tokens to google.oauth2.credentials.Credentials format
for use with Google API client libraries.
Args:
session: OAuth2Session with valid tokens
client_config: Client configuration subset (e.g., client_config['web'])
Returns:
Google Auth credentials object with tokens and configuration
Raises:
ValueError: If session has no access token (call fetch_token first)
"""from google_auth_oauthlib.helpers import session_from_client_config
# Client configuration dictionary
client_config = {
"installed": {
"client_id": "your-client-id.apps.googleusercontent.com",
"client_secret": "your-client-secret",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://oauth2.googleapis.com/token"
}
}
# Create session
session, config = session_from_client_config(
client_config,
scopes=['https://www.googleapis.com/auth/cloud-platform']
)
# Use session for OAuth flow
auth_url, state = session.authorization_url(
config['auth_uri'],
access_type='offline'
)from google_auth_oauthlib.helpers import session_from_client_secrets_file
# Load from file and create session
session, config = session_from_client_secrets_file(
'path/to/client_secrets.json',
scopes=['https://www.googleapis.com/auth/drive']
)
# Session is ready for OAuth flowfrom google_auth_oauthlib.helpers import credentials_from_session
import requests_oauthlib
# After completing OAuth flow with session
session = requests_oauthlib.OAuth2Session(client_id='...', scope=['...'])
# ... perform authorization flow ...
tokens = session.fetch_token('https://oauth2.googleapis.com/token', ...)
# Convert to Google Auth credentials
credentials = credentials_from_session(session, client_config)
# Use with Google API clients
from google.cloud import storage
storage_client = storage.Client(credentials=credentials)from google_auth_oauthlib.helpers import (
session_from_client_secrets_file,
credentials_from_session
)
# Step 1: Create session from client secrets
session, client_config = session_from_client_secrets_file(
'client_secrets.json',
scopes=['https://www.googleapis.com/auth/bigquery']
)
# Step 2: Generate authorization URL
auth_url, state = session.authorization_url(
client_config['installed']['auth_uri'],
access_type='offline'
)
print(f"Visit: {auth_url}")
auth_code = input("Enter authorization code: ")
# Step 3: Exchange code for tokens
session.fetch_token(
client_config['installed']['token_uri'],
code=auth_code,
client_secret=client_config['installed']['client_secret']
)
# Step 4: Convert to Google credentials
credentials = credentials_from_session(session, client_config['installed'])
# Step 5: Use credentials
from google.cloud import bigquery
bigquery_client = bigquery.Client(credentials=credentials)# Required configuration keys for client secrets
_REQUIRED_CONFIG_KEYS: frozenset = frozenset((
"auth_uri",
"token_uri",
"client_id"
))The helpers validate that client configurations contain all required keys and raise ValueError if any are missing.
Expected client secrets format:
{
"installed": {
"client_id": "your-client-id.apps.googleusercontent.com",
"client_secret": "your-client-secret",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://oauth2.googleapis.com/token"
}
}Or for web applications:
{
"web": {
"client_id": "your-client-id.apps.googleusercontent.com",
"client_secret": "your-client-secret",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://oauth2.googleapis.com/token",
"redirect_uris": ["http://localhost:8080/callback"]
}
}from google_auth_oauthlib.helpers import session_from_client_config
try:
session, config = session_from_client_config(client_config, scopes)
except ValueError as e:
print(f"Invalid client configuration: {e}")
# Either missing required keys or wrong format (not 'web' or 'installed')Install with Tessl CLI
npx tessl i tessl/pypi-google-auth-oauthlibevals
scenario-1
scenario-2
scenario-3
scenario-4
scenario-5
scenario-6
scenario-7
scenario-8
scenario-9
scenario-10