Надеюсь, это поможет, кстати, целевая аудитория - это URL-адрес, к которому вы хотите получить доступ.
import argparse
import google.auth
import google.auth.app_engine
import google.auth.compute_engine.credentials
import google.auth.iam
from google.auth.transport.requests import Request
import google.oauth2.credentials
from google.oauth2 import service_account
class AuthenticationConstants:
AUTHENTICATION_SCOPES_URL = 'https://www.googleapis.com/auth/cloud-platform'
OAUTH_TOKEN_URI = 'https://www.googleapis.com/oauth2/v4/token'
class JWT(object):
def __init__(self, service_account_key_path):
self.service_account_key_path = service_account_key_path
self.credentials = service_account.Credentials.from_service_account_file(
self.service_account_key_path)
self.scoped_credentials = self.credentials.with_scopes(
[AuthenticationConstants.OAUTH_TOKEN_URI])
def get_google_open_id_connect_token(self, target_audience):
signer_email = self.scoped_credentials.service_account_email
signer = self.scoped_credentials.signer
service_account_credentials = google.oauth2.service_account.Credentials(
signer,
signer_email,
token_uri=AuthenticationConstants.OAUTH_TOKEN_URI,
additional_claims={
'target_audience': target_audience
}
)
service_account_jwt = service_account_credentials._make_authorization_grant_assertion()
request = google.auth.transport.requests.Request()
body = {
'assertion': service_account_jwt,
'grant_type': google.oauth2._client._JWT_GRANT_TYPE,
}
token_response = google.oauth2._client._token_endpoint_request(
request, AuthenticationConstants.OAUTH_TOKEN_URI, body)
return token_response['id_token']
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument("--service-account-path")
parser.add_argument("--target-audience")
result = parser.parse_args()
jwt = JWT(result.service_account_path)
print(jwt.get_google_open_id_connect_token(result.target_audience))
Ниже приведен текст файла require.txt, который я использую:
google-api-python-client==1.7.11