Created
November 14, 2013 14:54
-
-
Save thomaswitt/7468182 to your computer and use it in GitHub Desktop.
Access Google Apps Admin SDK Directory API and retrieve all users from Google Apps
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
require 'rubygems' | |
require 'json' | |
require 'google/api_client' | |
require 'active_support/core_ext/hash' | |
# 1. Go to Google Cloud Console (https://cloud.google.com/console) | |
# 2. Create Service Account with P12 File | |
# 3. Enable the Admin SDK in APIs. | |
# 4. Create a Project | |
# 5. Create a registered app within this project | |
# 6. Go to section 'Certificate' and generate a key | |
# 7. Download the JSON file as well | |
# 8. Go to the Apps Console > Security > Extended > 3rdPartgy OAuth | |
# (https://admin.google.com/AdminHome?#OGX:ManageOauthClients) | |
# 9. Add a API Client. Client name is value of client_id in the JSON | |
# file, API Scope is https://www.googleapis.com/auth/admin.directory.user.readonly | |
# The value of client_email from the JSON file goes here | |
SERVICE_ACCOUNT_EMAIL = '[email protected]' | |
# This should be an Admin | |
ACT_ON_BEHALF_EMAIL = '[email protected]' | |
# File path to the certificate | |
SERVICE_ACCOUNT_PKCS12_FILE_PATH = 'client.p12' | |
key = Google::APIClient::PKCS12.load_key( | |
SERVICE_ACCOUNT_PKCS12_FILE_PATH, 'notasecret') | |
asserter = Google::APIClient::JWTAsserter.new(SERVICE_ACCOUNT_EMAIL, | |
'https://www.googleapis.com/auth/admin.directory.user.readonly', key) | |
client = Google::APIClient.new(:application_name => | |
'rubyapp.company.com') | |
client.authorization = asserter.authorize(ACT_ON_BEHALF_EMAIL) | |
api = client.discovered_api('admin', 'directory_v1') | |
result = client.execute( | |
:api_method => api.users.list, | |
:parameters => { | |
'domain' => 'company.com', | |
'orderBy' => 'givenName', | |
'maxResults' => 500, | |
'fields' => 'users(id,etag,primaryEmail,name,suspended)', | |
} | |
) | |
users = JSON.parse(result.body, {:symbolize_names => true})[:users] | |
users.each do |u| | |
puts "#{u[:name][:fullName]} <#{u[:primaryEmail]}> | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
if you want to use an RSA key instead of p12, use:
key = OpenSSL::PKey::RSA.new(GOOGLE_APPS_KEY_AS_STRING)