php - 如何使用 PHP 在我的服务器上验证 Android 生成的 token ?

标签 php android google-oauth google-play-services google-api-php-client

好吧,我一直在努力获得Tim Bray的文章描述的美妙必杀技Verifying Back-End Calls from Android Apps .我可以通过调用 GoogleAuthUtil.getToken() 从我的 Android 应用程序成功获取 token 。我将 token 作为 header Authorization Bearer 字段传递给我的 php 服务器。这就是我卡住的地方。

我现在应该做什么来验证 token 是从我的 Android 应用程序为与我的服务器项目相同的项目生成的?如何从 token 中获取 user_id?谢谢。

在 Google 控制台上,我的 php 服务器和 android 应用程序都在同一个项目中。在我的 php 服务器上,我可以链接 android/google-api-php-client/src/Google_Client.php 和 android/google-api-php-client/src/contrib/Google_PlusService.php 库代码。

最佳答案

好的,我终于找到了解决问题的方法。正如我所怀疑的,答案相当简单。我已经正确地做了很多事情。我的 Web 端点和我的 Android 应用程序都在同一个 Google API 控制台项目中。他们分享了Audience等项目条目。

我找到的所有用于验证的示例要么假设读者已经知道如何执行此操作,要么假设 PHP 需要生成 token 。最后无意中进入了Google OAuth2 documentation on Validating a Token这一段这让我想到了如何在我的 PHP 服务器上干净地进行验证。只是验证而已,妈妈! OAuth 已经够困惑了。还有其他用于从命令行使用 curl 进行验证的示例。但是,这就是您在 PHP 中调用 tokeninfo 以验证 (1) token 有效且 (2) 它适用于您的应用程序的方式。

$mToken = $_POST['mToken'];
$userinfo = 'https://www.googleapis.com/oauth2/v1/tokeninfo?id_token=' . $mToken;
$json = file_get_contents($userinfo);
$userInfoArray = json_decode($json,true);
$googleEmail = $userInfoArray['email'];
$tokenUserId = $userInfoArray['user_id'];
$tokenAudience = $userInfoArray['audience'];
$tokenIssuer = $userInfoArray['issuer'];    

if ( strcasecmp( $tokenAudience, GOOGLE_FULL_CLIENT_ID ) != 0) {
        error_log ( "ERROR:'" . $tokenAudience . "' did not match." );
}

变量 GOOGLE_FULL_CLIENT_ID 保存我的应用程序的受众字符串值(您可以从您的应用程序的 Google API 控制台定义页面复制它)。

在我的解决方案中,我决定使用 _POST 值对“mToken”将从我的 Android 应用程序生成的 token 传递到我的服务器端点。在 Android 中执行此操作的代码如下:

HttpPost httppost = new HttpPost("uri for your server web endpoint");
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("mToken", mToken));
try {
        HttpClient httpclient = new DefaultHttpClient();
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        HttpResponse response = httpclient.execute(httppost);
} catch (Exception e) {
        Log.e("HTTP", "Error in http connection " + e.toString());
}

关于php - 如何使用 PHP 在我的服务器上验证 Android 生成的 token ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17460977/

相关文章:

php - 将数组插入数据库

php - 字符串中的数字词转化为数字

android - 在 Kotlin 中创建一个 BaseView 类

C++ 如何使用 OpenSSL 验证 Google JWT (RS256)

google-openid - 哪种 Google 登录流程最适合 Web 应用程序?

php - 在 Controller 内调用 Twig 截断过滤器

javascript - 处理 UTC 日期客户端

android - 一个Java线程一次如何执行一个以上的 native 方法?

android - BroadcastReceiver:无法实例化类;没有空的构造函数

google-oauth - app inventor 2 使用私有(private)融合表