Search code examples
pythonamazon-web-servicesgoogle-authenticationaws-secrets-manager

Google Authentication in python


I am trying to get authentication to use the google translation API. Currently on my local machine I simply do this:

from google.cloud import translate_v2 as translate

os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = path_to_cred_json_file
translate_client = translate.Client()

which works fine. However, I wish to do this on AWS where I have I stored the credential json file in AWS secrets. In the documentation for translate.Client I see this:

Init signature:
translate.Client(
    target_language='en',
    credentials=None,
    ...
)
...

:type credentials: :class:`~google.auth.credentials.Credentials`

However, if I read in the json file and try to pass it in as the credentials argument it chucks an error.

The only answer I have for now in AWS is to read the secret, write it out as a json file, and then set os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = path_to_cred_json_file, which will work, but was told by a data engineer is a security risk.

So the question is how do I get this google.auth.credentials.Credentials object without reading a physical file. I have access to the plain text version of the json file in memory (via AWS secrets). I'm really new to AWS in general so go easy on me.


Solution

  • Thanks to @miles-budnek and this github comment, found the answer.

    Supposing I have the json string as a dictionary called secret:

    from google.cloud import translate_v2 as translate
    from google.oauth2 import service_account
    
    credentials = service_account.Credentials.from_service_account_info(secret) 
    t_client = translate.Client(credentials=credentials)