Authentication¶
Sign in from a local application¶
Follow Quickstart to create a desktop OAuth client and download its
configuration as client_secrets.json. PyDrive2 uses google-auth to
authorize requests to Drive.
from pydrive2.auth import GoogleAuth
gauth = GoogleAuth()
gauth.LocalWebserverAuth()
LocalWebserverAuth() opens the browser and
listens on localhost, trying port 8080 and then 8090 by default. If you use
a web application client, register the exact callback URI, such as
http://localhost:8080/, and pass port_numbers=[8080].
To open the sign-in URL yourself, call
gauth.LocalWebserverAuth(launch_browser=False) or
CommandLineAuth(). Both print the URL and
wait for the same local callback. The browser must be able to reach the
callback on the machine running PyDrive2. Unattended jobs can use a saved
refresh token or a service account. Set the GDRIVE_NON_INTERACTIVE
environment variable to any non-empty value to make
LocalWebserverAuth() raise AuthenticationError when it would
otherwise start a browser sign-in. 0 and false count as set.
Save credentials across runs¶
By default, GoogleAuth() reads client configuration from
client_secrets.json, requests the Drive scope, and keeps the access token
in memory. To reuse a login, create settings.yaml in your working
directory and sign in once.
client_config_backend: file
client_config_file: client_secrets.json
save_credentials: true
save_credentials_backend: file
save_credentials_file: credentials.json
get_refresh_token: true
The client configuration identifies your OAuth application. The separate
credentials.json file contains the user’s tokens. Give the application a
writable cache directory so it can lock and atomically replace the token
file on refresh. The lock is a credentials.json.lock file created
beside the token file. It can remain after the lock is released; whether
it does depends on the platform. In containers, mount the directory. For
an existing cache from an earlier release, see Upgrade to PyDrive2 2.0.
Request timeout¶
Drive requests and token refreshes use a socket timeout of 60 seconds. A
connect, send or read that makes no progress for that long fails, and a
Drive call then raises TimeoutError. A request that keeps making
progress can take longer. Change the limit with
GoogleAuth(http_timeout=120), or pass http_timeout=None to wait
without a limit. GDriveFileSystem takes the same option for the
sign-in it does itself.
The timeout does not cover the browser sign-in: LocalWebserverAuth()
and CommandLineAuth() exchange the authorization code over a separate
connection.
Settings reference¶
Pass a settings file path as GoogleAuth(settings_file="path/to/settings.yaml")
or supply a Python dictionary with GoogleAuth(settings=settings). A file
that is missing, unreadable or not valid YAML raises SettingsError.
Without a path, GoogleAuth() looks for settings.yaml in the working
directory and ignores it when it is missing.
client_config_backendUse
file(the default) to readclient_config_file,settingsto supply aclient_configdictionary, orservicewithservice_configfor a service account.client_configFor the
settingsbackend, provideclient_idandclient_secret. PyDrive2 supplies Google’sauth_uriandtoken_uriand defaultsredirect_uritohttp://localhost. For a web callback, setredirect_urito the URI registered for the client.oauth_scopeA list of OAuth scope URLs. The default is
https://www.googleapis.com/auth/drive. Choose scopes that grant access to the files your application needs.save_credentialsandget_refresh_tokenBoth default to false. Enable both to save the login and request offline access. Credentials loaded from a cache are written back to that cache when refreshed.
save_credentials_backendWhen saving credentials, select
filewithsave_credentials_file, ordictionarywithsave_credentials_dictandsave_credentials_key. To access the updated value in your program, pass the actual dictionary toGoogleAuth(settings=...).service_configSupply the JSON signing key as a path (
client_json_file_path), dictionary (client_json_dict), or JSON string (client_json). For a PKCS12 key, specify bothclient_pkcs12_file_pathandclient_service_email. For domain-wide delegation, setclient_user_emailto the user the account should act as.
Building your own authentication flow¶
For an application with its own web callback, configure a web OAuth client
and its registered redirect URI. Start a separate authorization flow per
login and keep the GoogleAuth instance and expected state in that user’s
server-side session until the callback. The flow holds the PKCE verifier
needed for the token exchange.
from secrets import compare_digest
from urllib.parse import parse_qs, urlsplit
def start_login():
gauth = GoogleAuth()
url = gauth.GetAuthUrl()
state = parse_qs(urlsplit(url).query)["state"][0]
return url, gauth, state
def finish_login(gauth, expected_state, callback_params):
if not compare_digest(expected_state, callback_params.get("state", "")):
raise ValueError("OAuth state mismatch")
gauth.Auth(callback_params["code"])
Redirect the user to the returned URL. On callback, retrieve and consume
the saved login from the session, then pass the decoded query parameters
to finish_login. If several workers handle requests, the callback
worker needs the original verifier as well as the expected state.
Authentication with a service account¶
Give the service account access to the Drive folder or files it will use. To create files, use a shared drive where it can write, or configure domain-wide delegation to act as a Workspace user with storage.
from pydrive2.auth import GoogleAuth
from pydrive2.drive import GoogleDrive
settings = {
"client_config_backend": "service",
"service_config": {"client_json_file_path": "service-account.json"},
}
gauth = GoogleAuth(settings=settings)
gauth.ServiceAuth()
drive = GoogleDrive(gauth)
Upgrading saved credentials¶
See Upgrade to PyDrive2 2.0 for the first login, token cache, and service-account changes in PyDrive2 2.0.