如何验证谷歌身份服务器端


How to validate Google identity server side

我有一个应用程序使用纯客户端Google API进行身份验证,并可能在圈子中列出联系人。但是,我将提交给服务器的某些数据与身份相关联。我究竟应该怎么做才能验证提交到我的服务器(我有一个 REST api)的身份实际上是经过身份验证的身份而不是伪造的?有没有一种好方法可以在不从服务器端进行 API 调用的情况下做到这一点?

我不太关心这个应用程序的安全性,但我想避免做任何非常愚蠢的事情。

您可以将从 Google 获得的 ID 令牌传递给服务器端。它是可以在本地验证的 JSON Web 令牌。除了正常的 JWT iss/exp/iat 和签名验证之外,您还要特别注意检查 audience 声明,以查看它是否确实颁发给了您的客户。

提问者编辑:在查看链接的文章后,我得出了以下代码,用于检索与 JWT.php一起使用的密钥:

<?php
$refresh = false;
if (file_exists('oauthkey')) {
   $age = time() - filemtime('oauthkey');
   if ($age > 20000)
      $refresh = true;   
} else
   $refresh = true;
if ($refresh) {
   $oauthKey = file_get_contents('https://www.googleapis.com/oauth2/v1/certs')
      or die('Failed to retrieve google public key.');
   $keyFile = fopen('oauthkey', 'w') or die ('Failed to open public key file for writing.');
   fwrite($keyFile, $oauthKey);
   fclose($keyFile);
} else {
   $keyFile = fopen('oauthkey', 'r') or die ('Failed to open public key file for reading.');
   $oauthKey = fread($keyFile, 5000) or die ('Failed to read from public key file.');
   fclose($keyFile);   
}
$oauthKey = json_decode($oauthKey, true);
?>