def authorize_service_account(json_credentials, scope, sub=None):
"""
authorize to the provide scope with a service credentials json file.
:param json_credentials: dictonary representing a service account, in most cases created from json.load
:param scope: scope(s) to authorize the application for
:param sub: User ID to authorize the application for (if needed)
:return Credentials to be used for http object
"""
try:
from oauth2client.service_account import ServiceAccountCredentials
except ImportError:
ServiceAccountCredentials = None
if ServiceAccountCredentials is not None and hasattr(ServiceAccountCredentials, "from_json_keyfile_dict"):
# running oauth2client version 2.0
creds = ServiceAccountCredentials.from_json_keyfile_dict(json_credentials, scope)
if sub is not None:
creds = creds.create_delegated(sub)
else:
try:
from oauth2client.client import SignedJwtAssertionCredentials
except ImportError:
raise EnvironmentError("Service account can not be used because PyCrypto is not available. Please install PyCrypto.")
if not isinstance(scope, (list, tuple)):
scope = [scope]
creds = SignedJwtAssertionCredentials(
service_account_name=json_credentials['client_email'],
private_key=json_credentials['private_key'],
scope=scope,
sub=sub)
return creds
评论列表
文章目录