I'm trying to execute a Google Cloud Function through PHP, but failing to authenticate when all I have is the service_account json file.
I'm using GuzzleHttp as the function returns a Promise.
What I did so far:
use Google\Auth\Credentials\ServiceAccountCredentials; use Google\Auth\Middleware\AuthTokenMiddleware; use GuzzleHttp\Client; use GuzzleHttp\Exception\RequestException; use GuzzleHttp\HandlerStack; use Psr\Http\Message\ResponseInterface; $scopes = [ 'https://www.googleapis.com/auth/cloud-platform', ]; $credentials = new ServiceAccountCredentials($scopes, [ 'client_email' => "<email>", 'client_id' => "<client_id">, 'private_key' => "<private_key>", ]); $googleAuthTokenMiddleware = new AuthTokenMiddleware($credentials); $stack = HandlerStack::create(); $stack->push($googleAuthTokenMiddleware); $config = array('handler' => $stack,'auth' => 'google_auth'); $httpClient = new Client($config); $promise = $httpClient->requestAsync("POST", "<function_url>", ['json' => ['data' => ""]]); $promise->then( function (ResponseInterface $res) { echo "<pre>"; print_r($res->getBody()); echo "</pre>"; }, function (RequestException $e) { echo "<pre>"; print_r($e->getRequest()->getHeaders()); echo "</pre>"; echo $e->getMessage() . "\n"; echo $e->getRequest()->getMethod(); } ); $promise->wait(); References:
ServiceAccountCredentials: From namespace Google\Auth\Credentials;
AuthTokenMiddleware: From namespace Google\Auth\Middleware;
HandlerStack: From GuzzleHttp
Client: From GuzzleHttp
Http Response From Above Code
`401 Unauthorized` response: {"error":{"status":"UNAUTHENTICATED","message":"Unauthenticated"}} POST My Cloud Function
My Cloud Function checks for authentication as follow:
exports.testFunction = functions.https.onCall((data, context) => { if (!context.auth) { throw new functions.https.HttpsError('failed-precondition', 'The function must be called ' + 'while authenticated.'); } return "Hooraaay!"; }); What am I doing wrong? How can I successfully authenticate?
401 Unauthorizedresponse: {"error":{"status":"UNAUTHENTICATED","message":"Unauthenticated"}}. Weird I thinkAuthorization: Bearer tokenbut I am not sure.