简体   繁体   中英

Authenticating to the Google Admin Directory API

I'm trying to figure out how to authenticate to the Admin Directory API. My goal is to be able to create new GSuite users.

I have followed this guide https://github.com/jay0lee/GAM/wiki/CreatingClientSecretsFile to setup a client/id secret and service account with Domain-Wide Delegation.

I can successfully get a bearer token, however when I try to make a request to an endpoint I get a 403. I would expect I should be authenticated to this endpoint as I can successfully get all data using GAM, which is using the same credentials.

require 'googleauth'
require 'google/apis/admin_directory_v1'

scope = ["https://www.googleapis.com/auth/admin.directory.user.readonly", "https://www.googleapis.com/auth/admin.directory.user"]

authorizer = Google::Auth::ServiceAccountCredentials.make_creds(
  json_key_io: File.open('service_account.json'),
  scope: scope)

pload = authorizer.fetch_access_token!
token = pload["access_token"]

url = "https://www.googleapis.com/admin/directory/v1/users/my@email.com"
uri = URI.parse(url)
request = Net::HTTP::Get.new(uri)
request.content_type = "application/json"
request["Authorization"] = "Bearer #{token}"

req_options = {
  use_ssl: uri.scheme == "https",
}

response = Net::HTTP.start(uri.hostname, uri.port, req_options) do |http|
  http.request(request)
end

p response #=> <Net::HTTPForbidden 403 Forbidden readbody=true>

修复了服务帐户上的范围,并且一切正常。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM