简体   繁体   中英

Revoking Access Google API PHP

I'm trying to revoke the access from a web app. This is my code:

When the user do login:

$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;
}

And here is the code when I want to revoke the app:

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

The result is a NOT FOUND page saying The requested URL /v2/{ "error" : "invalid_token"} was not found on this server.

I'm not sure if this is the correct way to revoke the access. Thanks.

I tried your code and had the same error. Take a look at how you have concatenated the strings at:

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

PHP easily lets committing syntax errors over concatenated strings. The fixed that worked for me was:

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

And in case you need it, my complete code is:

  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); 
    }

I think this should work..

$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);``` 

Based on https://developers.google.com/accounts/docs/OAuth2WebServer#tokenrevoke

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM