Google Service Account Authentication PHP
Asked Answered
L

3

7

I am trying to authenticate a service account so that I can use the access token with the client JSON_API library.

I have viewed these articles:

https://code.google.com/p/google-api-php-client/source/browse/trunk/examples/prediction/serviceAccount.php
https://code.google.com/p/google-api-php-client/wiki/UsingTheLibrary

https://developers.google.com/storage/docs/authentication#service_accounts https://developers.google.com/accounts/docs/OAuth2#scenarios

Here's my PHP Code

<?php

require_once 'google-api-php-client/src/Google_Client.php';

const CLIENT_ID = "";
const SERVICE_ACCOUNT_NAME = "";
const KEY_FILE = "super secret path of course ;)";

$client = new Google_Client();

// Loads the key into PKCS 12 format
$key = file_get_contents(KEY_FILE);
$client->setAssertionCredentials(new Google_AssertionCredentials(
    SERVICE_ACCOUNT_NAME,
    array('https://www.googleapis.com/auth/prediction'),
    $key
  )
);

$client->setClientId(CLIENT_ID);
$auth = $client->authenticate();
print $auth ? "Returned true" : "Returned false";
print "<br>";
print is_null($client->getAccessToken()) ? "It's null" : "Works";

?>

Here's my output:

Returned true
It's null

Letendre answered 29/12, 2013 at 20:38 Comment(0)
L
1

I finally figured out how to authenticate using the PHP API library after using a mixture of different resources.

Here's my authentication class for the google php api libray

<?php
require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_StorageService.php';

class Model_Storage_Auth
{
    const CLIENT_ID = "someuniquenumber.apps.googleusercontent.com";
    const SERVICE_ACCOUNT_NAME = "[email protected]";
    const KEY_FILE = "/supersecretpath/key.p12";
    const ACCESS_TOKEN = 'access_token';
    const APP_NAME = 'My App Name';

    private $google_client;

    function __construct()
    {
        $this->google_client = new Google_Client();
        $this->google_client->setApplicationName(self::APP_NAME);
    }

    public function getToken()
    {
        if(!is_null($this->google_client->getAccessToken())){}
        elseif(!is_null(Session::get(self::ACCESS_TOKEN, null)))
        {
            $this->google_client->setAccessToken(Session::get(self::ACCESS_TOKEN, null));
        }
        else
        {
            $scope = array();
            $scope[] = 'https://www.googleapis.com/auth/devstorage.full_control';
            $key = file_get_contents(self::KEY_FILE);
            $this->google_client->setAssertionCredentials(new Google_AssertionCredentials(
                self::SERVICE_ACCOUNT_NAME,
                $scope,
                $key)
            );
            $this->google_client->setClientId(self::CLIENT_ID);
            Google_Client::$auth->refreshTokenWithAssertion();
            $token = $this->google_client->getAccessToken();
            Session::set(self::ACCESS_TOKEN, $token);
        }
        return $this->google_client->getAccessToken();
    }

}
Letendre answered 5/1, 2014 at 21:17 Comment(1)
This solution won't work with newer versions of the Google API client: github.com/googleapis/google-api-php-clientDikmen
D
1

This implementation works for newer versions of Google API Client:

$client = new Google\Client();
$client->setAuthConfig('/path/to/private-key.json');
$client->useApplicationDefaultCredentials();
$client->setScopes($scope);
$client->setApplicationName($appName);
$access_token = $client->fetchAccessTokenWithAssertion();
$bearerToken = $access_token['id_token'];

// Now you can authenticate API calls by adding the Authorization header:
// "Authorization: Bearer $bearerToken"

Be sure to set the right path to the private key JSON file and replace scopes and Application name as required.

For using the Google Client API:

composer require google/apiclient:^2.15.0

Reference: https://github.com/googleapis/google-api-php-client

Dikmen answered 5/1, 2024 at 19:7 Comment(0)
E
0

A couple things to check:

  • First, I assume that CLIENT_ID and SERVICE_ACCOUNT_NAME are being set to your actual client ID and service account name, not just empty strings, right?

  • Second, you're using the OAuth scope https://www.googleapis.com/auth/prediction but trying to use that to access GCS. You'll want to either use read-only, read-write, or full-control scope, which you can find here. For example, if you wanted read-write access, you'd use the scope https://www.googleapis.com/auth/devstorage.read_write.

Emulsifier answered 29/12, 2013 at 22:33 Comment(1)
Yes my CLIENT_ID and SERVIE_ACCOUNT_NAME are set to their correct values, and I set that URL in the scopes. Still getting the same output :\Letendre

© 2022 - 2025 — McMap. All rights reserved.