撤消访问Google API PHP

时间:2014-12-18 10:15:28

标签: php oauth-2.0 google-api

我正在尝试撤消来自网络应用的访问权限。这是我的代码:

当用户登录时:

$scriptUri = "http:...";

$client = new Google_Client();

$client->setAccessType('online');
$client->setApplicationName('xxx');
$client->setClientId('xxx');
$client->setClientSecret('xxx');
$client->setRedirectUri($scriptUri);
$client->setDeveloperKey('xxx'); // API key
$client->setScopes(array('https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/userinfo.profile'));

$oauth2 = new Google_Service_Oauth2($client);

if (isset($_GET['code']) && isset($_GET["google"])){
    $client->authenticate($_GET['code']);
    $token = $client->getAccessToken();
    $client->setAccessToken($token);
    $_SESSION['google_token'] = $token;
}

以下是我要撤销该应用时的代码:

$ch = curl_init("https://accounts.google.com/o/oauth2/revoke?token=".$_SESSION['google_token'].";");
curl_exec($ch);
curl_close($ch)

结果是一个NOT FOUND页面,显示The requested URL /v2/{ "error" : "invalid_token"} was not found on this server.

我不确定这是否是撤销访问权限的正确方法。 感谢。

2 个答案:

答案 0 :(得分:0)

我尝试了您的代码,并遇到了相同的错误。 看一下如何将字符串串联在一起:

$ch = curl_init("https://accounts.google.com/o/oauth2/revoke?token=".$_SESSION['google_token'].";");

PHP可以轻松地在连接的字符串上提交语法错误。对我有用的解决方法是:

$RevokeTokenURL="https://accounts.google.com/o/oauth2/revoke?token=".$_SESSION['google_token'];
$ch = curl_init($RevokeTokenURL);

如果您需要它,我的完整代码是:

  if(isset($_GET['action']) && $_GET['action'] == 'logout') {
      session_destroy();
      header('Location:'.$RedirectURL);
      $RevokeTokenURL="https://accounts.google.com/o/oauth2/revoke?token=".$_SESSION['google_token'];
      $ch = curl_init($RevokeTokenURL);
      curl_exec($ch);
      curl_close($ch); 
    }

答案 1 :(得分:-1)

我认为这应该有效..

$revokeURL = "https://accounts.google.com/o/oauth2/revoke?token=".$access_token;

$ch = curl_init();
$options = array(
CURLOPT_URL => $revokeURL,
CURLOPT_HEADER  =>  true, 
CURLOPT_RETURNTRANSFER  =>  true,
CURLOPT_SSL_VERIFYPEER => true, //verify HTTPS
CURLOPT_SSL_CIPHER_LIST => 'TLSv1'); //remove this line if curl SSL error  

curl_setopt_array($ch, $options); //setup

$response = curl_exec($ch); //run
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); //get HTTP code

if ($httpCode == 200)
{
echo "Success"; // .$response;
} 
else 
{
echo "Error : ".$httpCode."__".curl_error($ch);    
}
curl_close($ch);``` 
  

基于https://developers.google.com/accounts/docs/OAuth2WebServer#tokenrevoke