【问题标题】:How to validate Google identity server side如何验证 Google 身份服务器端
【发布时间】:2015-03-31 07:37:50
【问题描述】:
我有一个应用程序使用纯客户端 Google API 进行身份验证,并可能在圈子中列出联系人。但是,我将提交给服务器的某些数据与身份相关联。我到底应该做什么来验证提交给我的服务器的身份(我有一个 REST api)实际上是经过身份验证的身份而不是伪造的?有没有不从服务器端进行 API 调用的好方法?
我并不十分担心这个应用程序的安全性,但我想避免做任何极其愚蠢的事情。
【问题讨论】:
标签:
php
security
oauth-2.0
google-api
【解决方案1】:
您可以将从 Google 获得的 ID 令牌传递到服务器端。它是一个 JSON Web Token,您可以在本地进行验证。除了普通的 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);
?>
【讨论】:
-
哇,JSON 网络令牌看起来很棒!我在尝试实施验证时遇到了障碍。我从github.com/firebase/php-jwt/tree/master/Authentication 中获取了 JWT.php,但是当我从 Google 开发人员控制台的 OAuth 客户端 ID 将我的“客户端密码”传递给关键参数时,调用 openssl_verify 时 JWT 失败。错误是未捕获的异常“DomainException”,在 /home/shores/shores.enigmadream.com/drawperator/JWT.php:181 中显示消息“OpenSSL 无法验证数据:错误:0906D06C:PEM 例程:PEM_read_bio:no start line”。任何想法如何追查这个问题的根源?
-
您的 JWT 很可能不是使用共享密钥签署的,而是使用 Google 的公钥签署的。检查 jwt.io 处的 JWT 标头。如果它使用RS256 算法,则需要使用 Google 的公钥进行验证。见stackoverflow.com/questions/17634698/…