【发布时间】:2017-08-09 07:33:24
【问题描述】:
我想使用 Google 登录来验证我的 PHP 的帖子。在网页上有一个谷歌登录按钮(有效),然后各种功能将从谷歌获得的id_token发布到我的PHP:
function getAuth() {
var id_token = theUser.getAuthResponse().id_token;
var oReq = new XMLHttpRequest();
oReq.onload = function() {
console.log(this.responseText);
}
oReq.open("POST", "databaseAccess.php", true);
oReq.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
oReq.send("oc="+id_token);
}
在服务器端:
<?php
if (isset($_POST["oc"])) {
$code = $_POST["oc"];
$client_id = "xxxxxxxxxxx.apps.googleusercontent.com";
$redirect_uri = "http://myDomain/responder.html";
$client_secret = "xxxxxxxx";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://accounts.google.com/o/oauth2/v2/auth");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_FAILONERROR, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, array(
'response_type' => 'code',
'scope' => 'profile',
'client_id' => $client_id,
'redirect_uri' => $redirect_uri
));
$data = curl_exec($ch);
}
echo($data);
?>
但结果是“1”,我认为我不应该期待。
来自SO question 我也试过了:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://accounts.google.com/o/oauth2/token");
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_FAILONERROR, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, array(
'code' => $code,
'client_id' => $client_id,
'client_secret' => $client_secret,
'redirect_uri' => $redirect_uri,
'grant_type' => 'authorization_code'
));
$data = curl_exec($ch);
echo($data)
但这没有任何回报:来自 Google 的沉默。根据docs,我也可以做一个更简单的
https://www.googleapis.com/oauth2/v3/tokeninfo?id_token=XYZ123
所以在 PHP 文件中,我尝试了:
$data = http_build_query(array(
'id_token' => $code
));
echo("DATA: ".$data);
$context = stream_context_create(array(
'https' => array(
'method' => 'GET',
'header' => 'Content-Type: application/x-www-form-urlencoded',
'content' => $data
)
));
// Make POST request
$response = file_get_contents('https://www.googleapis.com/oauth2/v2/tokeninfo', false, $context);
echo("PHP OUT: ".$response);
这样我得到了错误:
either access_token, id_token, or token_handle required
在网络浏览器中输入:
https://www.googleapis.com/oauth2/v2/tokeninfo?id_token=xxx0Cc6
我从网页的 javascript 收到的有效令牌会给我一个适当的结果:
{
"issued_to": "8jijijijijijihb.apps.googleusercontent.com",
"audience": "8jijijijijijij20hb.apps.googleusercontent.com",
"user_id": "1128jijijijijij38756",
"expires_in": 2412,
"email": "me@googlemail.com",
"verified_email": true
}
希望有人能告诉我如何在我的 PHP 中收到这样的结果。在我的低端服务器上使用 PHP beta api 也被证明是徒劳的。
【问题讨论】:
标签: javascript php oauth-2.0 google-oauth