客户端无权使用此方法从 Service Account 中检索访问令牌"

作者: amanets创建于 2022年2月14日更新于 2025年8月21日
标签type: questionpriority: p3

PROBLEM / CAUSE: I am using google-php-api-client to create calendar event, with service account and set the subject, subject email address is my admin account, with out subject this is working but when i am set subject this is not working and given error Client is unauthorized to retrieve access tokens using this method, or client not authorized for any of the scopes requested, When i am calling throw google API this is working properly API Calling code is : define('CALENDAR_ID', <claendar_id>); /*********************** Start: Create access Token***********************************/ function base64url_encode($data) { return rtrim(strtr(base64_encode($data), '+/', '-_'), '='); }

function getJwtAssertion($private_key_file) { $json_file = file_get_contents($private_key_file); $info = json_decode($json_file); $private_key = $info->{'private_key'};

//{Base64url encoded JSON header}
$jwtHeader = base64url_encode(json_encode(array(
    "alg" => "RS256",
    "typ" => "JWT"
)));
//{Base64url encoded JSON claim set}
$now = time();
$jwtClaim = base64url_encode(json_encode(array(
    "iss" => <serviceaccount>,
    "sub" => <admin_email_address>,
    "scope" => "https://www.googleapis.com/auth/calendar",
    "aud" => "https://www.googleapis.com/oauth2/v4/token",
    "exp" => $now + 3600,
    "iat" => $now
)));

$data = $jwtHeader.".".$jwtClaim;

// Signature
$Sig = '';
openssl_sign($data,$Sig,$private_key,'SHA256');
$jwtSign = base64url_encode($Sig);
$jwtAssertion = $data.".".$jwtSign;
return $jwtAssertion;

}

function getGoogleAccessToken($private_key_file) { $result = [ 'success' => false, 'message' => '', 'token' => null ];
if(!file_exists($private_key_file)){ $result['message'] = 'Google json key file missing!'; return $result; } $jwtAssertion = getJwtAssertion($private_key_file); try { $payload = [ 'grant_type' => 'urn:ietf:params:oauth:grant-type:jwt-bearer', 'assertion' => $jwtAssertion ]; $url = 'https://oauth2.googleapis.com/token'; $ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
$data = json_decode(curl_exec($ch), true); $http_code = curl_getinfo($ch,CURLINFO_HTTP_CODE); if($http_code != 200){ $result['message'] = 'Error : Failed to access token';

    } else {
        $result['token'] = $data['access_token'];
        $result['success'] = true;
    }
} catch (RequestException $e) {
      $result['message'] = $e->getMessage();
}
return $result;

} $KEY_FILE_LOCATION =

内容来源: googleapis/google-api-php-client