google-cloud-python icon indicating copy to clipboard operation
google-cloud-python copied to clipboard

Document using JSON string to create credentials from service account.

Open tab1293 opened this issue 7 years ago • 8 comments

It would be beneficial to be able to create a client instance using a service account file whose JSON contents have already been loaded in to memory. Currently from_service_account_json only supports loading a service account file from disk. This makes it difficult to create a client in scenarios where you are loading service account JSON contents from some external service and don't necessarily want to store the contents in a file where your application is running.

tab1293 avatar Feb 05 '19 20:02 tab1293

As a workaround, you can use a tempfile:

import tempfile
from google.cloud.<apilib> import Client

with tempfile.NamedTemporaryFile() as temp:
    temp.write(json_service_account_bytes)
    temp.flush()
    client = Client.from_service_account_json(temp.name)

The file will be closed / deleted when the with block exits.

tseaver avatar Feb 06 '19 18:02 tseaver

Yeah, a tempfile can be used (that's actually what I'm currently doing) but avoiding storing the key on disk is better. You should be able to pass the JSON string directly to the client constructor.

tab1293 avatar Feb 08 '19 03:02 tab1293

@tab1293 @tseaver you could use a code similar to:

credentials = google.oauth2.service_account.Credentials.from_service_account_info(keyfile_dict, scopes=scopes)
client = VideoIntelligenceServiceClient(credentials)

Real use case: https://github.com/apache/airflow/blob/master/airflow/contrib/hooks/gcp_api_base_hook.py

mik-laj avatar Mar 12 '19 12:03 mik-laj

+1 to https://github.com/googleapis/google-cloud-python/issues/7291#issuecomment-471982254

I never really liked those factory functions. It's better to explicitly create a credentials object with the google-auth library.

tswast avatar May 30 '19 22:05 tswast

Rather than adding a from_service_account_json classmethod factory to each of the 95 or so clients which currently have from_service_account_file factories, let's instead just document how to construct credentials from JSON.

tseaver avatar Jul 26 '19 15:07 tseaver

are you kidding me that this is not supported?:D or is this just not updated as of yet?

simonobe avatar Dec 10 '20 10:12 simonobe

@busunkim96 Is it done?

mik-laj avatar Dec 16 '20 00:12 mik-laj

The PR was merged on December 14, and the details look up to date now with a working example. Please reopen if the update is insufficient. Thank you.

iennae avatar Apr 09 '21 00:04 iennae