Admin SDK,Directory API,Users:list - 有关如何执行此操作的任何PHP示例?

时间:2013-12-09 17:54:03

标签: php google-app-engine google-admin-sdk google-directory-api

  1. Google Apps for Business链接到Apps Engine帐户
  2. 云控制台 - >注册的应用 - > {name} - >网络应用程序 - > OAuth 2.0 ClientID
  3. 云控制台 - > Admin API(开启)
  4. Google Apps控制台 - >安全 - > API访问(已选中)
  5. “ -​​ >” - >第三方OAuth - > API客户端({ClientID} .apps.googleusercontent.com)
  6. “ -​​ >” - > “ - > API范围(https://www.googleapis.com/auth/admin.directory.user
  7. 这是我到目前为止所拥有的,

    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" } }
    

    在页面底部的Users: List示例中,他们会显示“获取”请求,如下所示,

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

    什么是{YOUR_API_KEY}?我已经尝试过每个云控制台和Google Apps API都没有运气。

    如果我使用完全不同的方法,我就是完全错了。我已经苦苦挣扎了一个多星期,并且会喜欢任何形式的回应。感谢

3 个答案:

答案 0 :(得分:2)

我认为实现这一目标的最简单方法是使用Google提供的PHP客户端库https://github.com/google/google-api-php-client/,它可以很好地为您处理auth内容。如果你试着自己动手,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);

答案 1 :(得分:0)

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

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

我确定您已阅读this,但您需要了解OAuth2 web flow以及client library如何利用您的使用情况。 您应该要求this file才能使用目录API。

答案 2 :(得分: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();