1

i'm trying to write a simple script that will get the users list from my Google G Suite domain from Directory API of Admin SDK using google-api-python-client. I've read tons of documentation, tried hundreds of various requests, but always receive: googleapiclient.errors.HttpError: <HttpError 403 when requesting https://www.googleapis.com/admin/directory/v1/users?domain=example.com&alt=json returned "Not Authorized to access this resource/api"> error.

This is what i did:

  1. In the Google Developer console https://console.developers.google.com:

    • created a new project
    • enabled 'Admin SDK' API.
    • created a Service account Key
    • saved the generated key into a 'service-key.json' file
  2. In the G Suite Admin console:

  3. Created a simple test script:

    #!/usr/bin/env python3
    
    import json
    from httplib2 import Http
    from oauth2client.service_account import ServiceAccountCredentials
    from apiclient.discovery import build
    
    scopes = ['https://www.googleapis.com/auth/admin.directory.user.readonly']
    
    credentials = ServiceAccountCredentials.from_json_keyfile_name(
        'service-key.json', scopes)
    
    account = credentials.authorize(Http())
    service = build('admin', 'directory_v1', http=account)
    response = service.users().list(domain='example.com').execute()
    
    print(response)
    

Other:

  • tried also 'Enable G Suite Domain-wide Delegation' (used create_delegated() method on a ServiceAccountCredentials object)
  • i see in the Google Developer Console - Dashboard, that the script is issuing the proper requests - can see the 'directory.users.list' API methods are being issued, but fails with 403 error

Thanks in advance for any help!

sbocinec
  • 181
  • 1
  • 5
  • 4
    Try [impersonating](https://stackoverflow.com/a/26469289/5995040) an admin of your domain, since you've were able to enable domain-wide delegation. As the link stated, "When your service account request and is not an administrator on the domain, so it cannot access the Admin SDK Directory API." Hope this helps. – Mr.Rebot Nov 11 '17 at 20:22
  • How do you do this in python? E.g. how would it look with the above code? – Elliptica Aug 14 '19 at 22:52
  • @Elliptica You can check [this](https://stackoverflow.com/questions/60262432/service-account-not-authorized-to-access-this-resource-api-while-trying-to-acces/60262433#60262433) answer for a Python solution – hilsenrat Feb 20 '20 at 11:46

1 Answers1

2

@Mr.Rebot's suggestion worked for me. The basic service account wouldn't work but impersonating the admin (which you have enabled it to do), allows the API call to pass.

AmaJayJB
  • 1,453
  • 2
  • 14
  • 21