LoginSignup
1
1

More than 5 years have passed since last update.

google-api-client Webブラウザをなしで認証

Last updated at Posted at 2018-10-09

rubyのサンプルが見つからなかったのでメモ

google api のサンプルがコンソールに表示されたurlからブラウザで認証キーを取得するという使い所のないものだったため、サーバサイドだけで完結できるものがないか調べて見た

perform G Suite Domain-Wide Delegation of Authority を参考に
1. https://console.cloud.google.com API認証からサービス アカウントを作成、その際に認証用ファイルをダウンロード
2. https://admin.google.com の https://admin.google.com/AdminHome?fral=1&chromeless=1#OGX:ManageOauthClients で1で作ったサービスアカウントIDとAPIスコープをカンマ区切りで承認を押下

google-api-clientもバージョンの違いで、ググっても混乱して大変だった

いくつかのサイトを参考にPKCS12ファイルでやって見たが

notFound: Domain not found. (Google::Apis::ClientError)

とエラーが出た

そこでサービス アカウントの認証ファイルをjson形式変更して下記のようにしてようやく動いた。管理権限のメールアドレスをauthorizationの際に指定する必要があるようだ


require 'google/apis/admin_directory_v1'
require 'googleauth'
#*** LOCAL GEMS ***
#google-api-client (0.24.2)
#googleauth (0.6.6)

SCOPE = [Google::Apis::AdminDirectoryV1::AUTH_ADMIN_DIRECTORY_USER,Google::Apis::AdminDirectoryV1::AUTH_ADMIN_DIRECTORY_GROUP]
ENV['GOOGLE_APPLICATION_CREDENTIALS']  = "./xxxxx-11111111-9e7053d****.json"

service = Google::Apis::AdminDirectoryV1::DirectoryService.new
authorization = Google::Auth.get_application_default(SCOPE).dup
authorization.sub = 'test@sample.com'
service.authorization = authorization
response = service.list_users(domain: 'sample.com',customer: 'my_customer', max_results: 100, order_by: 'email')
puts response.to_json


参考
Google Apps の Directory API にてWebブラウザを介さずに認証する

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1