如何识别 Google OAuth2 用户? [英] How to identify a Google OAuth2 user?

查看:28
本文介绍了如何识别 Google OAuth2 用户?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 Facebook 登录来识别用户.当新用户到来时,我将他们的用户 ID 存储在我的数据库中.下次他们来时,我认出了他们的 Facebook ID,我知道我数据库中的用户是哪个.

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.

现在我正在尝试对 Google 的 OAuth2 做同样的事情,但我如何识别用户?

Now I am trying to do the same with Google's OAuth2, but how can I recognize the users?

Google 向我发送了几个代码和令牌(access_token、id_token、refresh_token),但是它们都不是固定的.这意味着如果我注销并在 2 分钟后重新登录,则所有 3 个值都已更改.如何唯一标识用户?

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?

我正在使用他们的 PHP 客户端库:https://code.google.com/p/google-api-php-client/

I am using their PHP client library: https://code.google.com/p/google-api-php-client/

推荐答案

我把这个方法插入到google-api-php-client/src/apiClient.php:

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);  
}

现在我可以打电话了:

$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
)

解决方案源于此线程:https://groups.google.com/forum/#!msg/google-api-php-client/o1BRsQ9NvUQ/xa532MxegFIJ

这篇关于如何识别 Google OAuth2 用户?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆