使用带有SignedJwtAssertionCredentials的Google API Python客户端

时间:2015-04-10 18:47:23

标签: python oauth-2.0 google-oauth google-api-python-client

我正在尝试使用google_api_python_client-1.4.0从Google获取用户列表。即使我拥有域范围的委派权限,我也会收到access_denied错误。

有趣的是,当我使用与.net客户端库相同的证书/凭证时,它可以工作。

我得到的错误是   文件" /Library/Python/2.7/site-packages/oauth2client-1.4.6-py2.7.egg/oauth2client/client.py" ;,第807行,在_do_refresh_request中 oauth2client.client.AccessTokenRefreshError:access_denied:请求的客户端未经授权。

# Load the key in PKCS 12 format that you downloaded from the Google API
# Console when you created your Service account.
f = file('Gkeys/87ty8g87-privatekey.p12', 'rb')
key = f.read()
f.close()
# Create an httplib2.Http object to handle our HTTP requests and authorize it
# with the Credentials. Note that the first parameter, service_account_name,
# is the Email address created for the Service account. It must be the email
# address associated with the key that was created.
credentials = SignedJwtAssertionCredentials(
    '889h98h98h98h98h9lurk@developer.gserviceaccount.com',
    key,
    scope=['https://www.googleapis.com/auth/admin.directory.group.readonly','https://www.googleapis.com/auth/admin.directory.user.readonly'],
    private_key_password='notasecret',
    sub='admin.user@domain.com'

)


http = httplib2.Http()
http = credentials.authorize(http)


directory_service = build('admin', 'directory_v1', http=http)

all_users = []
page_token = None

params = {'groupKey': 'groupname@domain.com'}

while True:
  try:
    if page_token:
      params['pageToken'] = page_token
    #current_page = directory_service.users().list(**params).execute()
    #current_page = directory_service.members().list(**params).execute()
    current_page = directory_service.members().list(groupKey='groupname@domain.com').execute()

    all_users.extend(current_page['users'])
    page_token = current_page.get('nextPageToken')
    if not page_token:
      break
  except errors.HttpError as error:
    print 'An error occurred: %s' % error
    break

for user in all_users:
  print user['primaryEmail']

1 个答案:

答案 0 :(得分:1)

您确定控制面板中授权的示波器与您在此处请求的范围完全匹配吗?如果您授权读/写范围并在此处使用只读范围,我认为这会导致您的错误。