Google Authentication
googleauthentication is a Python meta-package designed to simplify connecting to Google services by bundling and abstracting common patterns from official Google authentication libraries like `google-auth`, `google-auth-oauthlib`, and `google-api-python-client`. It provides helper functions to manage OAuth 2.0 flows for web and installed applications. The current version is 0.0.18, and it maintains an active, iterative release schedule typical for pre-1.0 libraries.
Common errors
-
FileNotFoundError: [Errno 2] No such file or directory: 'client_secrets.json'
cause The `client_secrets.json` file, which contains your Google Cloud project's OAuth 2.0 credentials, is missing or the provided path is incorrect.fixDownload `client_secrets.json` from your Google Cloud Console (APIs & Services -> Credentials -> Create Credentials -> OAuth client ID -> Web application/Desktop app) and place it in the working directory or provide its correct absolute path to `build_oauth_session` or `build_oauth_service`. -
google.auth.exceptions.RefreshError: ('invalid_grant: Bad Request', {'error': 'invalid_grant', 'error_description': 'Bad Request'})cause This usually indicates an issue with the OAuth refresh token, which can be due to incorrect scopes, revoked user permissions, an expired token (especially for sensitive scopes requiring re-authorization), or a mismatch in client ID/secret.fix1. Verify `client_secrets.json` credentials are correct and match your Google Cloud project. 2. Ensure all required scopes are specified and that the user has granted consent. 3. Delete the `token.json` file (if used) to force a re-authentication flow, prompting the user for consent again. 4. For internal-only apps, ensure the OAuth consent screen is configured correctly; for external apps, it must be published. -
AttributeError: module 'googleauthentication' has no attribute 'build_oauth_service'
cause The functions `build_oauth_session` and `build_oauth_service` (and the `OAuthSession` class) are not directly available under the top-level `googleauthentication` package but reside within its `oauth_session` submodule.fixChange your import statement from `from googleauthentication import build_oauth_service` to `from googleauthentication.oauth_session import build_oauth_service`.
Warnings
- breaking As a pre-1.0 library (version 0.0.x), `googleauthentication` is subject to frequent and potentially undocumented breaking changes between minor versions. API signatures or internal behaviors may change without strict adherence to semantic versioning.
- gotcha The library includes `oauth2client` as a dependency, which is largely deprecated and superseded by `google-auth` and `google-auth-oauthlib` for new development. While `googleauthentication` attempts to integrate them, this mix of legacy and modern libraries could lead to confusion or potential conflicts if other parts of your application rely on specific versions or patterns of Google authentication.
- gotcha The official documentation for `googleauthentication` is minimal, relying heavily on understanding the underlying Google client libraries (e.g., `google-auth`, `google-api-python-client`). This can make troubleshooting or advanced usage challenging without prior knowledge of those libraries.
Install
-
pip install googleauthentication
Imports
- build_oauth_session
from googleauthentication import build_oauth_session
from googleauthentication.oauth_session import build_oauth_session
- build_oauth_service
from googleauthentication import build_oauth_service
from googleauthentication.oauth_session import build_oauth_service
- OAuthSession
from googleauthentication import OAuthSession
from googleauthentication.oauth_session import OAuthSession
Quickstart
import os
import json
from googleauthentication.oauth_session import build_oauth_service
# --- Create a dummy client_secrets.json for this example ---
# In a real scenario, this file is downloaded from Google Cloud Console.
# DO NOT hardcode secrets in production code.
client_secrets_path = "client_secrets.json"
dummy_client_secrets_content = {
"web": {
"client_id": os.environ.get("GOOGLE_CLIENT_ID", "YOUR_CLIENT_ID"),
"project_id": "registry-test-project",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://oauth2.googleapis.com/token",
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
"client_secret": os.environ.get("GOOGLE_CLIENT_SECRET", "YOUR_CLIENT_SECRET"),
"redirect_uris": [
"http://localhost:8080/",
"http://localhost"
]
}
}
with open(client_secrets_path, "w") as f:
json.dump(dummy_client_secrets_content, f)
# ---------------------------------------------------------
SCOPES = ['https://www.googleapis.com/auth/drive.metadata.readonly']
TOKEN_FILE = 'token.json'
try:
# Build an authenticated Google Drive service
print("Attempting to build Google Drive service...")
drive_service = build_oauth_service(
api_name='drive',
api_version='v3',
client_secrets_json=client_secrets_path,
scopes=SCOPES,
token_file=TOKEN_FILE
)
print("Service built successfully.")
# Example: List up to 5 files
print("Fetching files...")
results = drive_service.files().list(
pageSize=5, fields="nextPageToken, files(id, name)").execute()
items = results.get('files', [])
if not items:
print("No files found in your Google Drive.")
else:
print("Files:")
for item in items:
print(f" {item['name']} ({item['id']})")
except Exception as e:
print(f"An error occurred during authentication or API call: {e}")
finally:
# Clean up dummy files created for the example
if os.path.exists(client_secrets_path):
os.remove(client_secrets_path)
if os.path.exists(TOKEN_FILE):
os.remove(TOKEN_FILE)
print("Cleanup complete.")