服务器端的授权google OAuth 2.0,如何检查令牌?

时间:2019-06-03 19:05:56

标签: javascript php google-oauth google-api-php-client

我无法在服务器端验证用户令牌ID。在Google的指南中做了 https://developers.google.com/identity/sign-in/web/backend-auth

在JS中,我获得了id令牌并将其发送到服务器

var googleUser = auth2.currentUser.get(),
    id_token = googleUser.getAuthResponse().id_token;

var xhr = new XMLHttpRequest();
xhr.open('POST', 'http://api.site.loc//tokensignin');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.onload = function() {
      console.log('Signed in as: ' + xhr.responseText);
};
xhr.send('idtoken=' + id_token);

我在服务器上接受

$CLIENT_ID = '.apps.googleusercontent.com';
$id_token = $formData['idtoken'];

$client = new Google_Client(['client_id' => $CLIENT_ID]);
$payload = $client->verifyIdToken($id_token);
if ($payload) {
   $userid = $payload['sub'];
  // If request specified a G Suite domain:
  //$domain = $payload['hd'];
} else {
  // Invalid ID token
}

结果是我收到此错误,而不是确认令牌

<b>Fatal error</b>:  Uncaught exception 'LogicException' with message 'id_token must be passed in or set as part of setAccessToken' in \google-api-php-client\src\Google\Client.php:717

1 个答案:

答案 0 :(得分:1)

该错误归因于$id_token为空(空)的事实。 因此,如果您遇到此类问题,请检查$id_token是否正确

感谢John Hanley的帮助