1

I'm trying to solve a task using Admin SDK API - Get the user-list from domain - Сhange users password

For my case i created a service user in G Suite and wrote the script from the example below:

from oauth2client.service_account import ServiceAccountCredentials
from httplib2 import Http
from apiclient.discovery import build

def main():
    scopes = ['https://www.googleapis.com/auth/admin.directory.user']

    credentials = ServiceAccountCredentials.from_json_keyfile_name('paswd.json', scopes=scopes)
    http_auth = credentials.authorize(Http())
    service = build('admin', 'directory_v1', http=http_auth)

    print('Getting the first 10 users in the domain')
    results = service.users().list(customer='my_customer', maxResults=10, orderBy='email', domain='nnn.nn').execute()
    print(results)

if __name__ == '__main__':
    main()

When I execute script, I got the next exception:

Getting the first 10 users in the domain
Traceback (most recent call last):
  File "./run-2.py", line 25, in <module>
    main()
  File "./run-2.py", line 21, in main
    results = service.users().list(customer='my_customer', maxResults=10, orderBy='email', domain='nnn.nn').execute()
  File "/usr/local/lib/python3.4/dist-packages/oauth2client/_helpers.py", line 133, in positional_wrapper
    return wrapped(*args, **kwargs)
  File "/usr/local/lib/python3.4/dist-packages/googleapiclient/http.py", line 840, in execute
    raise HttpError(resp, content, uri=self.uri)
googleapiclient.errors.HttpError: <HttpError 403 when requesting https://www.googleapis.com/admin/directory/v1/users?customer=my_customer&domain=g.nsu.ru&alt=json&maxResults=10&orderBy=email returned "Not Authorized to access this resource/api">

What could be the problem?

Ivan Kolesnikov
  • 1,787
  • 1
  • 29
  • 45
  • Your error is similar to this [SO thread](http://stackoverflow.com/questions/39011470/google-admin-sdk-403-not-authorized-to-access-this-resource-api) and seems to have been resolved. – ReyAnthonyRenacia Mar 22 '17 at 13:52

1 Answers1

2

As far as I have been able to figure out, what you are missing is:

credentials = ServiceAccountCredentials.from_json_keyfile_name('paswd.json', scopes=scopes)
delegated_credentials = credentials.create_delegated(DELEGATED_ACCOUNT)
http_auth = delegated_credentials.authorize(Http())

Where DELEGATED_ACCOUNT is an admin for your domain.