0
  1. 与 Apps Engine 帐户关联的 Google Apps for Business
  2. Cloud Console -> 注册应用程序 -> {name} -> Web 应用程序 -> OAuth 2.0 ClientID
  3. Cloud Console -> Admin API(开启)
  4. Google Apps 控制台 -> 安全 -> API 访问(选中)
  5. “ ->” -> 3rd 方 OAuth -> API 客户端 ({ClientID}.apps.googleusercontent.com)
  6. “->”->“-> API 范围(https://www.googleapis.com/auth/admin.directory.user

这是我到目前为止所拥有的,

require_once 'google/appengine/api/app_identity/AppIdentityService.php';
use \google\appengine\api\app_identity\AppIdentityService;

function setAuthHeader() {
  $access_token =AppIdentityService::getAccessToken("https://www.googleapis.com/auth/admin.directory.user");
  return [ sprintf("Authorization: OAuth %s", $access_token["access_token"]) ];
}

$get_contacts_url = "https://www.googleapis.com/admin/directory/v1/users?customer=my_customer";
$headers = implode("\n\r", setAuthHeader());
$opts =
  array("http" =>
  ["http" => ["header" => $headers ]]
);
$context = stream_context_create( $opts );
$response = file_get_contents( $get_contacts_url, false, $context );
print_r ($response);

“access_token”通过就好了,但 $response 返回,

{ "error": { "errors": [ { "domain": "global", "reason": "required", "message": "Login Required", "locationType": "header", "location": "Authorization" } ], "code": 401, "message": "Login Required" } }

在页面底部的用户:列表示例中,它们显示“获取”请求,如下所示,

GET https://www.googleapis.com/admin/directory/v1/users?customer=my_customer&key={YOUR_API_KEY}

{YOUR_API_KEY} 是什么?我已经尝试了所有 Cloud Console 和 Google Apps API,但都没有成功。

我完全错了,我应该使用完全不同的方法吗?我已经为此苦苦挣扎了一个多星期,并且希望得到任何回应。谢谢

4

3 回答 3

4

我认为最简单的方法是使用谷歌提供的 PHP 客户端库https://github.com/google/google-api-php-client/,它在处理身份验证方面做得很好为你。如果您尝试自己动手,JWT 的东西会变得非常棘手。我只是为你整理了一个例子,https://gist.github.com/fillup/9fbf5ff35b337b27762a。我使用自己的 Google Apps 帐户对其进行了测试,并验证了它可以正常工作,如果您遇到问题,请告诉我。

编辑:为方便起见,在此处添加代码示例:

<?php
/**
 * Easiest to use composer to install google-api-php-client and generate autoloader
 * If you dont want to use composer you can manually include any needed files
 */
include_once 'vendor/autoload.php';

/**
 * Client ID from https://console.developers.google.com/
 * Must be added in Google Apps Admin console under Security -> Advanced -> Manage API client     access
 * Requires scope https://www.googleapis.com/auth/admin.directory.user or
 * https://www.googleapis.com/auth/admin.directory.user.readonly
 */
$clientId = 'somelongstring.apps.googleusercontent.com';

/**
 * Service Account Name or "Email Address" as reported on     https://console.developers.google.com/
 */
$serviceAccountName = 'somelongstring@developer.gserviceaccount.com';

/**
 * Email address for admin user that should be used to perform API actions
 * Needs to be created via Google Apps Admin interface and be added to an admin role
 * that has permissions for Admin APIs for Users
 */
$delegatedAdmin = 'delegated-admin@domain.com';

/**
 * This is the .p12 file the Google Developer Console gave you for your app
 */
$keyFile = 'file.p12';

/**
 * Some name you want to use for your app to report to Google with calls, I assume
 * it is used in logging or something
 */
$appName = 'Example App';

/**
 * Array of scopes you need for whatever actions you want to perform
 * See https://developers.google.com/admin-sdk/directory/v1/guides/authorizing
 */
$scopes = array(
    'https://www.googleapis.com/auth/admin.directory.user'
);

/**
 * Create AssertionCredentails object for use with Google_Client
 */
$creds = new Google_Auth_AssertionCredentials(
    $serviceAccountName,
    $scopes,
    file_get_contents($keyFile)
);
/**
 * This piece is critical, API requests must be used with sub account identifying the
 * delegated admin that these requests are to be processed as
 */
$creds->sub = $delegatedAdmin;

/**
 * Create Google_Client for making API calls with
 */
$client = new Google_Client();
$client->setApplicationName($appName);
$client->setClientId($clientId);
$client->setAssertionCredentials($creds);

/**
 * Get an instance of the Directory object for making Directory API related calls
 */
$dir = new Google_Service_Directory($client);

/**
 * Get specific user example
 */
//$account = $dir->users->get('example@domain.com');
//print_r($account);

/**
 * Get list of users example
 * In my testing you must include a domain, even though docs say it is optional
 * I was getting an error 400 without it
 */
$list = $dir->users->listUsers(array('domain' => 'domain.com', 'maxResults' => 100));
print_r($list);
于 2014-10-23T16:03:26.103 回答
0

简而言之:您过度简化了 OAuth2。

这并不像通过密钥作为 HTTP GET 参数发送来获取数据那么容易。

我确定您已经阅读了这篇文章,但您需要了解OAuth2 Web 流程以及客户端 如何为您利用该用法。您应该需要此文件才能使用 Directory API。

于 2013-12-10T14:53:34.573 回答
0

您使用的是最新的 PHP 库还是已弃用的库?对于最新的 BETA PHP 库,这是与身份验证部分相关的代码部分。

set_include_path("google-api-php-client-master/src/" . PATH_SEPARATOR . get_include_path());
require_once 'Google/Client.php';
require_once 'Google/Auth/OAuth2.php';

if (isset($_SESSION['service_token'])) {
  $client->setAccessToken($_SESSION['service_token']);
}

$key = file_get_contents($key_file_location);

$cred = new Google_Auth_AssertionCredentials(
  // Replace this with the email address from the client.
  $clientEmail,
  // Replace this with the scopes you are requesting.
  array(SCOPES),
  $key
);
$cred->sub = ""; //admin email
$client->setAssertionCredentials($cred);

try {
if($client->getAuth()->isAccessTokenExpired()) {
  $client->getAuth()->refreshTokenWithAssertion($cred);
}

$_SESSION['service_token'] = $client->getAccessToken();
于 2014-06-08T16:20:12.063 回答