How to authenticate REST API request when using service account credentials?

126 views Asked by At

I am trying to use the REST API to get search results for an app with unstructured data, using the servingConfigs.search method from the documentation here.

I am using the service account key as the 'GOOGLE_APPLICATION_CREDENTIALS' environment variable, however in the header of the REST request it requires an access token. Simply using

shell_exec(gcloud auth application-default print-access-token)

I cannot get the access token.

When i manually run the command i can generate the access token and the authorisation works. However using shell_exec() to run the gcloud commands returns null.

Is there a different library or something i can use to get this access token?

I tried to generate an access token to authorise the REST request, however it only works when i manually generate the token via CLI. I have tried using relative and absolute paths for the gcloud command but neither give me the result i expect.

1

There are 1 answers

0
Holt Skinner On

Here is the documentation for how to handle authentication in a local development environment.

https://cloud.google.com/docs/authentication/provide-credentials-adc#local-dev

Based on your use of the exec_shell() function, it seems like you're using PHP for your application.

The Google Cloud PHP Client Library repository shows how to authenticate using a local service account JSON file.

https://github.com/googleapis/google-cloud-php/blob/main/AUTHENTICATION.md

And here is the Code Sample for the PHP Client Library of Vertex AI Search

https://cloud.google.com/generative-ai-app-builder/docs/preview-search-results#genappbuilder_search-php