简体   繁体   English

适用于Android的PHP Google OAuth2后端

[英]PHP Google OAuth2 Backend for Android

I followed this tutorial ( http://blog.jachobsen.com/2013/08/10/google-oauth2-in-android-with-rails-backend/ ) to create the android part of the oauth2 authentication. 我按照本教程( http://blog.jachobsen.com/2013/08/10/google-oauth2-in-android-with-rails-backend/ )创建了oauth2身份验证的android部分。 At the end it provides the Rails part of the code for the server backend but I'm not very good with Rails and so am not too sure how to do it. 最后,它提供了服务器后端代码的Rails部分,但是我对Rails不太满意,因此也不太确定该怎么做。

Does anyone know how I could create something similar but with PHP instead? 有谁知道我可以用PHP创建类似的东西吗? I've had a look at this https://code.google.com/p/google-api-php-client/ but I haven't been able to edit the code to get the access token, check if is valid and then return an API key. 我已经看过了这个https://code.google.com/p/google-api-php-client/,但是我无法编辑代码以获取访问令牌,检查是否有效以及然后返回一个API密钥。

Thank you very much, Daniel 非常感谢,丹尼尔

The PHP sample you are looking at is not the latest for Google+ / authroization. 您要查看的PHP示例不是最新的Google+ /身份验证。 You should start from the latest content in the Google+ documentation: 您应该从Google+文档中的最新内容开始:

Google+ PHP Quickstart Google+ PHP快速入门

The quickstart shows you how to authorize the client and pass the credentials to your PHP backend for API calls. 快速入门向您展示如何授权客户端并将凭证传递给PHP后端以进行API调用。

If your server won't run Phar, you can get started with the sample code from the PHP client library page you linked and can update it to perform code exchange based on the code passed to your Android app or to authorize the user with an access token / authorization code from the web. 如果您的服务器无法运行Phar,则可以从链接的PHP客户端库页面开始使用示例代码,并可以对其进行更新,以根据传递给您的Android应用的代码进行代码交换,或授权用户访问来自网络的令牌/授权代码。

The following example performs code exchange for the web (as is done in the /connect endpoint in the quickstart sample): 以下示例执行Web的代码交换(如quickstart示例中的/ connect端点中一样):

<?php
require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_PlusService.php';

// Set your cached access token. Remember to replace $_SESSION with a
// real database or memcached.
session_start();

$client = new Google_Client();
$client->setApplicationName('Google+ PHP Starter Application');
// Visit https://code.google.com/apis/console?api=plus to generate your
// client id, client secret, and to register your redirect uri.
$client->setClientId('YOUR_CLIENT_ID');
$client->setClientSecret('YOUR_CLIENT_SECRET');
$client->setDeveloperKey('YOUR_SIMPLE_API_KEY');

$plus = new Google_PlusService($client);

if (isset($_GET['webcode'])) {
  $client->setRedirectUri('postmessage');
  $client->authenticate($_GET['webcode']);
  $_SESSION['token'] = $client->getAccessToken();

  $activities = $plus->activities->listActivities('me', 'public');
  print 'Your Activities: <pre>' . print_r($activities, true) . '</pre>';
}

To see the code work, you will need to generate a code from the web client: 要查看代码的工作原理,您将需要从Web客户端生成代码:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
</head>
<body>
<span id="signinButton">
<span
      class="g-signin"
      data-callback="signinCallback"
      data-clientid="YOUR_CLIENT_ID"
      data-cookiepolicy="single_host_origin"
      data-requestvisibleactions="http://schemas.google.com/AddActivity"
      data-scope="https://www.googleapis.com/auth/plus.login">
    </span>
  </span>
  <table>
    <tr>
      <th>Code</th><th>ID Token</th><th>Access token</th>
    </tr>
    <tr>
      <td><textarea id="code"></textarea></td>
      <td><textarea id="idtok"></textarea></td>
      <td><textarea id="atok"></textarea></td>
    </tr>
  </table>

  <script type="text/javascript">
      (function () {
          var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
          po.src = 'https://apis.google.com/js/client:plusone.js';
          var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
      })();

      function signinCallback(resp) {
          console.log(resp);
          document.getElementById('code').value = resp.code;
          document.getElementById('idtok').value = resp.id_token;
          document.getElementById('atok').value = resp.access_token;
      }
  </script>
</body>
</html>

And then will pass it to the php script as the webcode parameter. 然后将其作为webcode参数传递给php脚本。 I created a demo that runs from wheresgus.com/phptest/stackdemo.php and you can generate a code from http://wheresgus.com/phptest/gencode.html 我创建了一个从wheresgus.com/phptest/stackdemo.php运行的演示,您可以从http://wheresgus.com/phptest/gencode.html生成代码

An example GET would look like: GET示例如下所示:

http://wheresgus.com/phptest/stackdemo.php?webcode=4/ajfCXQiZo-zRBAJGktP_eSYRha2s.YiEFJjWUiW4bEnp6UAPFm0GQNJMGhgI

In practice, you should be POSTing your code over HTTPS; 实际上,您应该通过HTTPS发布代码; but to get you started, hopefully this helps. 但是,为了帮助您入门,希望对您有所帮助。

For your mobile clients, you should be able to verify using the ID token as follows: 对于移动客户端,您应该能够使用ID令牌进行验证,如下所示:

  • Securely pass the ID token to your application 安全地将ID令牌传递到您的应用程序
  • Verify the token is valid and belongs to the correct app 验证令牌是否有效并属于正确的应用
  • Use the sub field to identify your user 使用子字段标识您的用户

The following code shows a function in the same app that verifies the token and uses simple API access to perform activities.list for the signed-in user: 以下代码显示了同一应用程序中的一个功能,该功能可验证令牌并使用简单的API访问权限为登录用户执行activity.list:

if (isset($_GET['idtoken'])) {
  $attributes = $client->verifyIdToken($_GET['idtoken'], CLIENT_ID)
      ->getAttributes();
  $gplus_id = $attributes["payload"]["sub"];

  // At a minimum, make sure the token was for this app.
  if ($attributes["payload"]["aud"] == $client->getClientId()){
    $activities = $plus->activities->listActivities($gplus_id, 'public');
    print 'Your Activities: <pre>' . print_r($activities, true) . '</pre>';
  }else{
    print 'Authorization failed.';
  }
}

Full code available here . 完整的代码在这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM