CNSKnight
CNSKnight

Reputation: 577

Google API's Service Account Client Authorization Server-to-Server (Offline Impersonate) Errors

@note The involved server flow uses google-api-php-client-beta

The goal is to 'insert' an email 'message' into a Google for Work gmail account addressed to a registered email alias.

For this OAuth workflow, I have:

The following server code attempts to acquire a Google_Client authorized with the above Credentials and Access Token, while asking for the OAuth Client to impersonate the GFW User mentioned. Thereafter the $client can be used to call services such as Google_Service_Gmail.

Currently, the $authCreds is returned with ['error_description'] => 'Could not determine client ID from request' error message

// local const's for testing
const CLNT_GOOGL_SRVC_ACCT_CREDS = '';
const CLNT_GOOGL_API_SRVC_ACCT_CLIENT_ACCESS_CODE = '';
/**
* Returns an authorized API client.
* @return Google_Client the authorized client object
*/
private static function getAuthorizedClient() {
    $client = new Google_Client();
    $isSrvcAcct = false;

    if (self::CLNT_GOOGL_SRVC_ACCT_CREDS) {
        $isSrvcAcct = true;
        $creds = json_decode(self::CLNT_GOOGL_SRVC_ACCT_CREDS, true);
    } elseif (defined('CLNT_GOOGL_SRVC_ACCT_CREDS')) {
        $isSrvcAcct = true;
        $creds = json_decode(CLNT_GOOGL_SRVC_ACCT_CREDS, true);
    }

    if ($isSrvcAcct) {
        if (! isset($creds)) {
            acapApp::catchProcessMessage('CLNT_GOOGL_SRVC_ACCT_CREDS  is not valid JSON?', ACAP_DEBUG);

            return;
        }

        self::setServiceClient($client, (array) $creds);
    } else {
        self::setUserClient($client);
    }

    if ($client->getAccessToken()) {
        return $client;
    }
}

private static function setServiceClient(Google_Client $client, array $creds) {
    $client->setAuthConfig($creds);
    $client->setSubject(CLNT_SMTP_OAUTH_USER_EMAIL);

    if (self::CLNT_GOOGL_API_SRVC_ACCT_CLIENT_ACCESS_CODE) {
        $authCode = self::CLNT_GOOGL_API_SRVC_ACCT_CLIENT_ACCESS_CODE;
    } else if (defined('CLNT_GOOGL_API_SRVC_ACCT_CLIENT_ACCESS_CODE')) {
        $authCode = CLNT_GOOGL_API_SRVC_ACCT_CLIENT_ACCESS_CODE;
    }

    if (isset($authCode)) {
        $authCreds = $client->fetchAccessTokenWithAuthCode($authCode);
        if (isset($authCreds['error'])) {
            acapApp::catchProcessMessage('Failure Fetching Auth Token: '.$authCreds['error_description'], ACAP_DEBUG);
        }
    }
}

Upvotes: 0

Views: 2689

Answers (2)

jpcaparas
jpcaparas

Reputation: 181

Ensure that you're setting the authorisation config prior to fetching the access token with the auth code.

For example:

<?php
$client->setAuthConfig(storage_path('app/google_client_id.json'));
$token = $client->fetchAccessTokenWithAuthCode($code);

Upvotes: 1

Sneazel
Sneazel

Reputation: 11

If you use the .json file u have to use this for auth: $client->fetchAccessTokenWithAssertion()

Upvotes: 1

Related Questions