问题描述
我使用Facebook登录来识别用户。当新用户来到时,我将他们的用户ID存储在我的数据库中。下一次,他们来了,我认出他们的Facebook ID,并且知道它在我的数据库中是哪个用户。现在我正在尝试对Google的OAuth2执行相同的操作,我可以识别用户吗?
Google向我发送了几个代码和令牌(access_token,id_token,refresh_token),但是它们都不是常量。意思是如果我在2分钟后注销并重新登录,则所有3个值都已更改。我如何唯一标识用户?
我正在使用他们的PHP客户端库:
解决方案
php prettyprint-override> public function getUserInfo()
{
$ req = new apiHttpRequest('https://www.googleapis.com/oauth2/v1/userinfo') ;
// XXX错误处理丢失,这只是一个粗略的草案
$ req = $ this-> auth->符号($ req);
$ resp = $ this-> io-> makeRequest($ req) - > getResponseBody();
返回json_decode($ resp,1);
}
现在我可以打电话:
$ client-> setAccessToken($ _ SESSION ['token']);
$ userinfo = $ client-> getUserInfo();
它返回一个这样的数组(如果已经请求了该范围,则加上电子邮件): >
Array
(
[id] => 1045636599999999999
[名称] => Tim Strehle
[given_name] => Tim
[family_name] => Strehle
[locale] => de
)
解决方案来源于此主题:
I used Facebook login to identify users. When a new user comes, I store their userID in my database. Next time they come, I recognized their Facebook ID and I know which user it is in my database.
Now I am trying to do the same with Google's OAuth2, but how can I recognize the users?
Google sends me several codes and tokens (access_token, id_token, refresh_token), however none of them are constant. Meaning if I log out and log back in 2 minutes later, all 3 values have changed. How can I uniquely identify the user?
I am using their PHP client library: https://code.google.com/p/google-api-php-client/
I inserted this method into google-api-php-client/src/apiClient.php:
public function getUserInfo()
{
$req = new apiHttpRequest('https://www.googleapis.com/oauth2/v1/userinfo');
// XXX error handling missing, this is just a rough draft
$req = $this->auth->sign($req);
$resp = $this->io->makeRequest($req)->getResponseBody();
return json_decode($resp, 1);
}
Now I can call:
$client->setAccessToken($_SESSION[ 'token' ]);
$userinfo = $client->getUserInfo();
It returns an array like this (plus e-mail if that scope has been requested):
Array
(
[id] => 1045636599999999999
[name] => Tim Strehle
[given_name] => Tim
[family_name] => Strehle
[locale] => de
)
The solution originated from this thread: https://groups.google.com/forum/#!msg/google-api-php-client/o1BRsQ9NvUQ/xa532MxegFIJ
这篇关于如何识别Google OAuth2用户?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!