失败前提条件:必须是G Suite域用户,在ruby中使用服务帐户管理联系人

t1qtbnec  于 2023-06-29  发布在  Ruby
关注(0)|答案(1)|浏览(122)

我正试图使用ruby脚本和google API客户端管理我的google workplace用户服务帐户上的联系人。
下面是代码

require 'google/apis/people_v1'
require 'googleauth'
require 'byebug'

# Set up authorization
scopes = ['https://www.googleapis.com/auth/contacts', 'https://www.googleapis.com/auth/directory.readonly']
credentials = Google::Auth::ServiceAccountCredentials.make_creds(
  json_key_io: File.open('g_suite_service_account.json'),
  scope: scopes,
)

# Authorize the client
client = Google::Apis::PeopleV1::PeopleServiceService.new
client.authorization = credentials

# Fetch contacts
response = client.list_person_directory_people(
  sources: 'DIRECTORY_SOURCE_TYPE_DOMAIN_CONTACT',
  read_mask: 'addresses,clientData,emailAddresses,names,phoneNumbers'
)

byebug
puts ''

我是这么做的
1.使用google workplace云控制台创建服务帐户。
1.将服务帐户分配给google workplace管理员作为域范围的委派。

我仍然得到这个错误failedPrecondition: Must be a G Suite domain user. (Google::Apis::ClientError)
有人能帮我指出我在哪里/错过了什么吗?谢谢你

fhg3lkii

fhg3lkii1#

当使用域范围的委派时,您需要指定服务帐户将模拟域中的哪个用户。在当前版本的代码中,API调用是使用service account标识进行的,这导致了报告的错误。
您可以使用.sub方法指定用户:

# Set up authorization
scopes = ['https://www.googleapis.com/auth/contacts', 'https://www.googleapis.com/auth/directory.readonly']
credentials = Google::Auth::ServiceAccountCredentials.make_creds(
  json_key_io: File.open('g_suite_service_account.json'),
  scope: scopes,
)

credentials.sub = 'A_DOMAIN_USER@your_domain.com'

通过这样做,Google服务器中的API调用将使用模拟用户的身份执行。

Google文档:

  • 服务器到服务器应用程序-准备进行授权API调用

相关问题