Saw
Saw

Reputation: 6416

Authenticate Google Cloud vision without using environment variables (set credentials by code)

I am trying to connect to Google Cloud Vision from an AWS lambda function, the only way to authenticate seems to be by setting a certain environment variable, is there a way to authenticate using code (I am planning to store credentials details in AWS Secrets Manager and passing them through to the Google Vision client in Python).

The constructor of vision.ImageAnnotatorClient takes Credentials as the first parameter, but frustratingly, I am not able to construct such an object for a set of service account credentials!

Hope someone can help!

EDIT In this link, it seems that languages other than Python, there is something to help with parsing credentials, but not with the Python example!

https://cloud.google.com/docs/authentication/production#auth-cloud-explicit-python

Upvotes: 0

Views: 1989

Answers (3)

SEMICS
SEMICS

Reputation: 431

I had a similar issue and was fixed by a combination between other answers.

You need to create a credentials object using the service_account from google.oauth2 and the full path to your credentials.json file.

Then use this credentials object in vision.ImageAnnotatorClient.

from google.cloud import vision
from google.oauth2 import service_account

credentials = service_account.Credentials.from_service_account_file('PATH/TO/FILE.json')

client = vision.ImageAnnotatorClient(credentials=credentials)

Upvotes: 3

Dustin Ingram
Dustin Ingram

Reputation: 21520

You can put your credentials in a service_account.json file and do:

from google.cloud import vision

client = vision.Client.from_service_account_json('service_account.json')

Upvotes: 1

Saw
Saw

Reputation: 6416

Was not an easy find :( Here is the code to do that:

service_account_info_string = R"""{
    "type": "service_account",
    "project_id": "",
    "private_key_id": "",
    "private_key": "-----BEGIN PRIVATE KEY-----\n.......\n-----END PRIVATE KEY-----\n",
    "client_email": "[email protected]",
    "client_id": "545................45648",
    "auth_uri": "https://accounts.google.com/o/oauth2/auth",
    "token_uri": "https://oauth2.googleapis.com/token",
    "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
    "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/....%40....iam.gserviceaccount.com"
    }
    """

service_account_info_json = json.loads(service_account_info_string)

service_account_creds = creds.from_service_account_info(service_account_info_json)

client = vision.ImageAnnotatorClient(credentials=service_account_creds)

Upvotes: 4

Related Questions