一段时间后,Google Admin SDK未经授权的客户端PHP可以正常运行

时间:2017-12-13 09:00:55

标签: php oauth-2.0 google-api google-admin-sdk

需要有关Google管理员SDK的帮助。我是谷歌管理员SDK的新手。因此,在授权时我仍然坚持显示错误:

  

{错误:" unauthorized_client"," error_description":"客户端是   未经授权使用此方法检索访问令牌" }

这是我的代码。

<?php 

include_once '../vendor/autoload.php';
include_once "base.php";
session_start();
echo pageHeader("Service Account Access");


/************************************************
  Make an API request authenticated with a service
  account.
 ************************************************/
$client = new Google_Client();
$client->setAuthConfig('service_account.json');

$client->setApplicationName("automate user");
$client->setSubject('admin@******.org');

$client->setScopes(['https://www.googleapis.com/auth/admin.directory.user']);

$client->setIncludeGrantedScopes(true);
$client->setAccessType('offline');
//$auth_url = $client->createAuthUrl();

//header('Location: '.filter_var($auth_url, FILTER_SANITIZE_URL));

if(isset($_SESSION['access_token']) && $_SESSION['access_token'])
{
    $client->setAccessToken($_SESSION['access_token']);

    if ($credentials_file = checkServiceAccountCredentialsFile()) {
  // set the location manually
  $client->setAuthConfig('client_secret1.json');
} elseif (getenv('GOOGLE_APPLICATION_CREDENTIALS=service_account.json')) {
  // use the application default credentials
  $client->useApplicationDefaultCredentials();
} else {
  echo missingServiceAccountDetailsWarning();
  return;
}

$dir = new Google_Service_Directory($client);
$user = new Google_Service_Directory_User();
$name = new Google_Service_Directory_UserName();


//$results = $dir->users->get('********@****.com');
$name->setGivenName('*****');
$name->setFamilyName('*****');
$user->setName($name);
$user->setHashFunction('SHA-1');
$user->setPrimaryEmail('****@***');
$user->setpassword(hash('sha1','******'));
$user->setchangePasswordAtNextLogin(false);


$results = $dir->users->insert($user);

if($results) {
     echo "New user : ".$results->primaryEmail."";
} else{
     echo " User doesn't exist : ".$email;
}

} 
else {

if ($client->isAccessTokenExpired()) {
    $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
    //file_put_contents($credentialsPath, json_encode($client->getAccessToken()));
  }
    $redirect_uri = 'http://'.$_SERVER['HTTP_HOST']. '/google/oauth.php';
    header('Location: '.filter_var($redirect_uri, FILTER_SANITIZE_URL));
}


<?php pageFooter(__FILE__); ?>

第一次完美运作。几天后我运行此代码,显示错误unauthorized_client。我不知道为什么会出现这个错误。我已经创建了域范围的委托服务帐户。请帮忙告诉我的错误

1 个答案:

答案 0 :(得分:0)

您可以试试这个github论坛:

API access using own credentials (server to server flow)

  

第1步 - 创建OAuth2凭据

     

按照您用于生成服务的产品的步骤进行操作   使用JSON密钥文件的帐户,然后返回此页面。

     

第2步 - 设置客户端库

     

在adsapi_php.ini文件的[OAUTH2]部分下,插入   您的JSON密钥文件的路径,并设置您所在的广告API的范围   访问。插入您想要的用户的电子邮件帐户   冒充,如果有的话。