How to use Google API credentials json on Heroku?

后端 未结 10 1407
深忆病人
深忆病人 2020-12-03 05:36

I\'m making an app using Google Calendar API, and planning to build it on Heroku.
I have a problem about authentication. Usually I use credential json file for that, but

10条回答
  •  渐次进展
    2020-12-03 06:05

    If anyone is still looking for this, I've just managed to get this working for Google Cloud Storage by storing the JSON directly in an env variable (no extra buildpacks).

    You'll need to place the json credentials data into your env vars and install google-auth

    Then, parse the json and pass google credentials to the storage client:

    from google.cloud import storage
    from google.oauth2 import service_account
    
    # the json credentials stored as env variable
    json_str = os.environ.get('GOOGLE_APPLICATION_CREDENTIALS')
    # project name
    gcp_project = os.environ.get('GCP_PROJECT') 
    
    # generate json - if there are errors here remove newlines in .env
    json_data = json.loads(json_str)
    # the private_key needs to replace \n parsed as string literal with escaped newlines
    json_data['private_key'] = json_data['private_key'].replace('\\n', '\n')
    
    # use service_account to generate credentials object
    credentials = service_account.Credentials.from_service_account_info(
        json_data)
    
    # pass credentials AND project name to new client object (did not work wihout project name)
    storage_client = storage.Client(
        project=gcp_project, credentials=credentials)
    

    Hope this helps!

    EDIT: Clarified that this was for Google Cloud Storage. These classes will differ for other services, but from the looks of other docs the different Google Client classes should allow the passing of credentials objects.

提交回复
热议问题