【问题标题】:Google OAuth 2.0 with Service account with PHP: "Invalid token format error"带有 PHP 服务帐户的 Google OAuth 2.0:“无效的令牌格式错误”
【发布时间】:2017-11-14 01:09:05
【问题描述】:

我已经创建了我的服务帐户,获得了 private_key 并委派了域范围的权限。

这是我尝试使用服务帐户进行身份验证但得到相同的“无效令牌格式错误”的代码:

session_start();
include_once 'google-api-php/vendor/autoload.php';

function getClient() {
$client = new Google_Client();
$client->setApplicationName('theName');
$client->setScopes('https://www.googleapis.com/auth/admin.directory.user.readonly');
$client->setAccessType('offline');
$client->setSubject('admin@domain.com');
$client->setAuthConfig('private_key.json');

// Load previously authorized credentials from a file.
$credentialsPath = 'private_key.json';
if (file_exists($credentialsPath)) {
    $accessToken = json_decode(file_get_contents($credentialsPath), true);
}
else {
    // Request authorization from the user.
    $authUrl = $client->createAuthUrl();
    printf("Open the following link in your browser:\n%s\n", $authUrl);
    print 'Enter verification code: ';
    $authCode = trim(fgets(STDIN));

    // Exchange authorization code for an access token.
    $accessToken = $client->fetchAccessTokenWithAuthCode($authCode);

    // Store the credentials to disk.
    if(!file_exists(dirname($credentialsPath))) {
      mkdir(dirname($credentialsPath), 0700, true);
    }
    file_put_contents($credentialsPath, json_encode($accessToken));
    printf("Credentials saved to %s\n", $credentialsPath);
}

$client->setAccessToken($accessToken);

// Refresh the token if it's expired.
if ($client->isAccessTokenExpired()) {
    $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
    file_put_contents($credentialsPath, json_encode($client->getAccessToken()));
}
return $client;
}

这是我之前从 $accessToken 得到的截图

$client->setAccessToken($accessToken);

错误本身:

https://postimg.org/image/ajgan5y27/

任何帮助将不胜感激。谢谢!

【问题讨论】:

    标签: php oauth-2.0 google-api-php-client google-admin-sdk service-accounts


    【解决方案1】:

    问题在于过时的 google api 文档。 原来“getClient”功能的新版本只需要这个就可以工作,以防万一有人遇到麻烦:

    function getClient() {
        $client = new Google_Client();
        $client->setAuthConfig('private_key.json');
        $client->setApplicationName('theName');
        $client->setScopes(Google_Service_Sheets::SPREADSHEETS_READONLY);
        return $client;
    }
    

    不需要 $client->setAccessToken();完全...

    谷歌干得好...这些是我从以下代码中获取的过时且不可靠的文档页面:

    https://developers.google.com/admin-sdk/directory/v1/quickstart/phphttps://developers.google.com/api-client-library/php/auth/service-accounts

    还有一点:如果您需要使用 Google 表格,您可能需要添加帐户服务 ID (xxxxxxxxxx@xxxxxxxxxxxxxx.iam.gserviceaccount.com ) 到您要从中提取信息的 google sheet 文档。

    【讨论】:

    • 现在是 2019 年,文档仍然过时,所以 +1 帮助我。
    • 在添加此功能后得到 UNAUTHENTICATED 401 错误@Le Caboom
    猜你喜欢
    • 2012-04-05
    • 1970-01-01
    • 2014-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-25
    • 1970-01-01
    • 2013-07-17
    相关资源
    最近更新 更多