【问题标题】:Google php api authentication exception谷歌php api认证异常
【发布时间】:2015-06-09 05:59:08
【问题描述】:

我正在尝试使用 Outh2 验证 google 服务帐户,但不断收到此错误 -

异常 - 刷新 OAuth2 令牌时出错,消息:'{ "error" : "access_denied", "error_description" : "请求的客户端不 授权。”}'

我已按照https://developers.google.com/api-client-library/php/auth/service-accounts 的所有指示进行操作 我也确实从谷歌管理控制台授权了服务帐户,但仍然没有运气。任何人都可以建议下面的代码是否有任何问题-

$client_email = aab123@developer.gserviceaccount.com';
        $private_key = file_get_contents('private_key_file_location.p12');
        $scopes = array('https://spreadsheets.google.com/feeds');
        $user_to_impersonate = 'user@example.com';
        $credentials = new Google_Auth_AssertionCredentials($client_email, $scopes, 
                                                            $private_key, 'notasecret',
                                                           'http://oauth.net/grant_type/jwt/1.0/bearer',
                                                           $user_to_impersonate);

        $client = new Google_Client();

        $client->setApplicationName('Portal Assessment Module');
        $client->setAccessType('offline');

        $client->setAssertionCredentials($credentials);
        if ($client->getAuth()->isAccessTokenExpired()) {
            $client->getAuth()->refreshTokenWithAssertion($credentials);    /* Exception 
is being triggered here */    
}

谢谢。

【问题讨论】:

    标签: google-api-php-client


    【解决方案1】:

    试试这个

    require_once realpath(dirname(__FILE__).'/google-api-php-client/src/Google/autoload.php');
    
    define('SCOPES', implode(' ', array(Google_Service_Appsactivity::DRIVE)));
    
    $credentials = new Google_Auth_AssertionCredentials(
        $client_email,
        SCOPES,
        $private_key
    );
    
    $client = new Google_Client();
    $client->setAssertionCredentials($credentials);
    
    if ($client->getAuth()->isAccessTokenExpired())
    {
        $client->getAuth()->refreshTokenWithAssertion();
    }
    
    print_r($client->getAccessToken());
    

    【讨论】:

    • 感谢您的代码,但使用我发布的答案使其正常工作
    【解决方案2】:

    终于弄明白了,必须确保 $user_to_impersonate 与 $client_email 相同,并且该电子邮件地址具有对电子表格的编辑权限。

    $user_to_impersonate = $client_email
    

    【讨论】:

      猜你喜欢
      • 2018-09-02
      • 2023-03-05
      • 1970-01-01
      • 2014-01-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多